mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 07:26:52 +01:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eff67f1159 | ||
|
|
a3dc54b012 | ||
|
|
e8d6cd9b58 | ||
|
|
d190ac7446 | ||
|
|
05410034e3 | ||
|
|
cbcf441d7c | ||
|
|
4b295e086e | ||
|
|
35b3d92bdd | ||
|
|
7c2dcd7ba1 | ||
|
|
4d42378537 | ||
|
|
cb9ab9c516 | ||
|
|
6c6bf5e486 | ||
|
|
d102107f2e | ||
|
|
b92806d199 | ||
|
|
437d47ffc5 | ||
|
|
bd82089a3f | ||
|
|
1d0281cba5 | ||
|
|
dff5c51dd6 | ||
|
|
656164b259 | ||
|
|
84e28c62ea | ||
|
|
6885bac85d | ||
|
|
5c5d6e3314 | ||
|
|
0aa15ef247 | ||
|
|
2ecf2f738e | ||
|
|
1bf0bf382c | ||
|
|
19578b3b6b | ||
|
|
5edcaefa33 | ||
|
|
bbade4dc9a | ||
|
|
cbf8146bda | ||
|
|
3b850c6ecf | ||
|
|
a508a4e22c | ||
|
|
e7b2abb0b2 | ||
|
|
5cc53c22db | ||
|
|
70e7d3f2ea | ||
|
|
4ce04760ae | ||
|
|
1e6a95df15 | ||
|
|
4d37a3140f | ||
|
|
b26c1e9c3e | ||
|
|
5c5254dc18 | ||
|
|
ab89556c5c | ||
|
|
1a8fb8d67e | ||
|
|
73ddb56c34 |
No files matched your search
@@ -14,7 +14,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -40,7 +40,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -83,7 +83,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
# GitHub holds ARNs, not credentials, and ARNs outlive a rotation
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: add hashicorp source
|
||||
@@ -66,7 +66,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: add hashicorp source
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
# WSL2 + Ubuntu so the smoke can run a real linux peer with its own
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Smoke Docker
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: build
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Install goimports
|
||||
@@ -87,7 +87,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Build
|
||||
@@ -132,7 +132,7 @@ jobs:
|
||||
|
||||
- uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: '1.26'
|
||||
go-version: '1.27'
|
||||
check-latest: true
|
||||
|
||||
- name: Build ${{ matrix.name }}
|
||||
|
||||
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- Version 3 certificates and post-quantum hybrid handshakes (`ix_hybrid_mlkem1024`). A version 3 certificate is a
|
||||
version 2 certificate extended with a post-quantum key and a deterministic post-quantum CA signature, and a node
|
||||
holding one still presents the version 2 certificate it extends to peers that need it. Its post-quantum suite names
|
||||
the algorithms, as its curve does the classical ones; the one suite today is `MLKEM1024_MLDSA87`, an ML-KEM-1024
|
||||
key for hosts and ML-DSA-87 for CAs and their signatures, chosen with `nebula-cert -pq-suite`. `nebula-cert
|
||||
pq-extend` upgrades existing CAs and hosts in place, and extending a certificate twice gives the same certificate.
|
||||
See `docs/pq-handshake.md`.
|
||||
|
||||
### Changed
|
||||
|
||||
- A version 3 certificate has two fingerprints: its own, and that of the version 2 certificate it extends. Both
|
||||
identify it in logs and to `pki.blocklist`. **To block a version 3 certificate, block its v2 fingerprint**: the
|
||||
pool checks it for the v3 certificate and for its v2 form alike, so that one entry covers both forms. Blocking only
|
||||
the v3 fingerprint leaves the v2 form usable in classical handshakes. `nebula-cert print` leads with both
|
||||
fingerprints and says which one to block; in JSON they are `fingerprint` and `v2Fingerprint`.
|
||||
- Firewall `ca_sha` rules match a version 3 peer by either fingerprint of its CA.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
||||
|
||||
+55
-1
@@ -15,6 +15,11 @@ import (
|
||||
type CAPool struct {
|
||||
CAs map[string]*CachedCertificate
|
||||
certBlocklist map[string]struct{}
|
||||
|
||||
// v3CAs indexes the version 3 CAs in CAs by the fingerprint of their v2 form, which is what the certificates
|
||||
// they issue name as issuer. A version 3 CA only verifies version 3 certificates: version 2 certificates find
|
||||
// their issuer in CAs, where only the v2 form of the CA, if listed itself, answers to that fingerprint.
|
||||
v3CAs map[string]*CachedCertificate
|
||||
}
|
||||
|
||||
// NewCAPool creates an empty CAPool
|
||||
@@ -22,6 +27,7 @@ func NewCAPool() *CAPool {
|
||||
ca := CAPool{
|
||||
CAs: make(map[string]*CachedCertificate),
|
||||
certBlocklist: make(map[string]struct{}),
|
||||
v3CAs: make(map[string]*CachedCertificate),
|
||||
}
|
||||
|
||||
return &ca
|
||||
@@ -122,6 +128,17 @@ func (ncp *CAPool) AddCA(c Certificate) error {
|
||||
cc.InvertedGroups[g] = struct{}{}
|
||||
}
|
||||
|
||||
if v2 := V2Form(c); v2 != nil {
|
||||
v2Sum, err := v2.Fingerprint()
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not calculate fingerprint for provided CA; error: %w; %s", err, c.Name())
|
||||
}
|
||||
if other, ok := ncp.v3CAs[v2Sum]; ok && other.Fingerprint != sum {
|
||||
return fmt.Errorf("%s: two version 3 CAs extend the same version 2 CA %s", c.Name(), v2Sum)
|
||||
}
|
||||
ncp.v3CAs[v2Sum] = cc
|
||||
}
|
||||
|
||||
ncp.CAs[sum] = cc
|
||||
|
||||
if c.Expired(time.Now()) {
|
||||
@@ -180,11 +197,34 @@ func (ncp *CAPool) VerifyCertificate(now time.Time, c Certificate) (*CachedCerti
|
||||
return nil, ErrBlockListed
|
||||
}
|
||||
|
||||
// Blocking the v2 form of a version 3 certificate blocks the certificate too.
|
||||
var v2Fps []string
|
||||
if v2 := V2Form(c); v2 != nil {
|
||||
v2Fp, err := v2.Fingerprint()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not calculate v2 fingerprint to verify: %w", err)
|
||||
}
|
||||
v2Fp2, err := CalculateAlternateFingerprint(v2)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not calculate alternate v2 fingerprint to verify: %w", err)
|
||||
}
|
||||
v2Fps = append(v2Fps, v2Fp)
|
||||
if v2Fp2 != "" {
|
||||
v2Fps = append(v2Fps, v2Fp2)
|
||||
}
|
||||
for _, f := range v2Fps {
|
||||
if ncp.IsBlocklisted(f) {
|
||||
return nil, ErrBlockListed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cc := CachedCertificate{
|
||||
Certificate: c,
|
||||
InvertedGroups: make(map[string]struct{}),
|
||||
Fingerprint: fp,
|
||||
fingerprint2: fp2,
|
||||
v2Fingerprints: v2Fps,
|
||||
signerFingerprint: signer.Fingerprint,
|
||||
}
|
||||
|
||||
@@ -202,6 +242,11 @@ func (ncp *CAPool) VerifyCachedCertificate(now time.Time, c *CachedCertificate)
|
||||
if c.fingerprint2 != "" && ncp.IsBlocklisted(c.fingerprint2) {
|
||||
return ErrBlockListed
|
||||
}
|
||||
for _, f := range c.v2Fingerprints {
|
||||
if ncp.IsBlocklisted(f) {
|
||||
return ErrBlockListed
|
||||
}
|
||||
}
|
||||
|
||||
_, err := ncp.verify(c.Certificate, now, c.Fingerprint, c.signerFingerprint)
|
||||
return err
|
||||
@@ -221,6 +266,10 @@ func (ncp *CAPool) verify(c Certificate, now time.Time, certFp string, signerFp
|
||||
return nil, ErrCurveMismatch
|
||||
}
|
||||
|
||||
if PQSuiteOf(signer.Certificate) != PQSuiteOf(c) {
|
||||
return nil, ErrPQSuiteMismatch
|
||||
}
|
||||
|
||||
if signer.Certificate.Expired(now) {
|
||||
return nil, ErrRootExpired
|
||||
}
|
||||
@@ -257,7 +306,12 @@ func (ncp *CAPool) GetCAForCert(c Certificate) (*CachedCertificate, error) {
|
||||
return nil, fmt.Errorf("no issuer in certificate")
|
||||
}
|
||||
|
||||
signer, ok := ncp.CAs[issuer]
|
||||
cas := ncp.CAs
|
||||
if c.Version() == Version3 {
|
||||
cas = ncp.v3CAs
|
||||
}
|
||||
|
||||
signer, ok := cas[issuer]
|
||||
if ok {
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
@@ -14,12 +14,14 @@ const (
|
||||
VersionPre1 Version = 0
|
||||
Version1 Version = 1
|
||||
Version2 Version = 2
|
||||
Version3 Version = 3
|
||||
)
|
||||
|
||||
type Certificate interface {
|
||||
// Version defines the underlying certificate structure and wire protocol version
|
||||
// Version1 certificates are ipv4 only and uses protobuf serialization
|
||||
// Version2 certificates are ipv4 or ipv6 and uses asn.1 serialization
|
||||
// Version3 certificates extend a Version2 certificate with post-quantum keys and signatures
|
||||
Version() Version
|
||||
|
||||
// Name is the human-readable name that identifies this certificate.
|
||||
@@ -115,6 +117,9 @@ type CachedCertificate struct {
|
||||
|
||||
// A place to store a 2nd fingerprint if the certificate could have one, such as with P256
|
||||
fingerprint2 string
|
||||
|
||||
// The fingerprints of a version 3 certificate's v2 form, which the blocklist also applies to
|
||||
v2Fingerprints []string
|
||||
}
|
||||
|
||||
func (cc *CachedCertificate) String() string {
|
||||
@@ -143,6 +148,8 @@ func Recombine(v Version, rawCertBytes, publicKey []byte, curve Curve) (Certific
|
||||
c, err = unmarshalCertificateV1(rawCertBytes, publicKey)
|
||||
case Version2:
|
||||
c, err = unmarshalCertificateV2(rawCertBytes, publicKey, curve)
|
||||
case Version3:
|
||||
c, err = unmarshalCertificateV3(rawCertBytes, publicKey, curve)
|
||||
default:
|
||||
return nil, ErrUnknownVersion
|
||||
}
|
||||
@@ -165,6 +172,12 @@ func CalculateAlternateFingerprint(c Certificate) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// The post-quantum signature of a version 3 certificate covers its classical signature, so it has no second form.
|
||||
// The pool checks the fingerprints of its v2 form separately.
|
||||
if c.Version() == Version3 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
nc := c.Copy()
|
||||
b, err := p256.Swap(nc.Signature())
|
||||
if err != nil {
|
||||
|
||||
+516
@@ -0,0 +1,516 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mldsa"
|
||||
"crypto/mlkem"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/cryptobyte"
|
||||
"golang.org/x/crypto/cryptobyte/asn1"
|
||||
)
|
||||
|
||||
// A version 3 certificate is a version 2 certificate extended with post-quantum keys. Its first fields are exactly
|
||||
// the fields of the v2 certificate it extends, so a v3 holder can always marshal that v2 form, byte for byte, and use
|
||||
// it with peers that only speak v2. The v2 form keeps its own classical CA signature and fingerprint.
|
||||
//
|
||||
// The certificate's PQSuite says which post-quantum algorithms it uses, the way its curve does for the classical
|
||||
// ones. Hosts carry a public key for the suite's KEM and CAs one for its signature algorithm. The issuing CA, which
|
||||
// has the same suite, signs every field with that signature algorithm, including the suite and the classical
|
||||
// signature, so neither can be swapped out. Signatures are deterministic, so a certificate extended twice is the same
|
||||
// certificate.
|
||||
//
|
||||
// Wherever a v3 certificate deals in keys they are composite: the classical key followed by the post-quantum one.
|
||||
// PublicKey returns classical || post-quantum, and VerifyPrivateKey and signing take the private keys the same way.
|
||||
|
||||
const (
|
||||
TagCertPQSuite = 4 | classContextSpecific
|
||||
TagCertPQPublicKey = 5 | classContextSpecific
|
||||
TagCertPQSignature = 6 | classContextSpecific
|
||||
)
|
||||
|
||||
// Sizes of the keys and signatures of PQSuite_MLKEM1024_MLDSA87.
|
||||
const (
|
||||
// MLKEM1024PublicKeySize is the size of an ML-KEM-1024 encapsulation key.
|
||||
MLKEM1024PublicKeySize = mlkem.EncapsulationKeySize1024
|
||||
// MLKEM1024PrivateKeySize is the size of an ML-KEM-1024 decapsulation key seed.
|
||||
MLKEM1024PrivateKeySize = mlkem.SeedSize
|
||||
// MLDSA87PublicKeySize is the size of an ML-DSA-87 public key.
|
||||
MLDSA87PublicKeySize = mldsa.MLDSA87PublicKeySize
|
||||
// MLDSA87PrivateKeySize is the size of an ML-DSA-87 private key seed.
|
||||
MLDSA87PrivateKeySize = mldsa.PrivateKeySize
|
||||
// MLDSA87SignatureSize is the size of an ML-DSA-87 signature.
|
||||
MLDSA87SignatureSize = mldsa.MLDSA87SignatureSize
|
||||
|
||||
// pqSignatureContext is the ML-DSA context string for certificate signatures.
|
||||
pqSignatureContext = "nebula certificate v3"
|
||||
)
|
||||
|
||||
type certificateV3 struct {
|
||||
// v2 is the version 2 certificate this one extends. Its public key is the classical key.
|
||||
v2 certificateV2
|
||||
|
||||
// pqSuite names the post-quantum algorithms, and so the kind of pqPublicKey and pqSignature.
|
||||
pqSuite PQSuite
|
||||
|
||||
// pqPublicKey is the suite's KEM public key of a host, or its signature algorithm's public key of a CA.
|
||||
pqPublicKey []byte
|
||||
|
||||
// pqSignature is the issuing CA's post-quantum signature over every other field.
|
||||
pqSignature []byte
|
||||
}
|
||||
|
||||
// V2Form returns the version 2 certificate a version 3 certificate extends, or nil for any other version. It is
|
||||
// what a v3 holder presents to peers that do not speak v3.
|
||||
func V2Form(c Certificate) Certificate {
|
||||
if c3, ok := c.(*certificateV3); ok {
|
||||
return &c3.v2
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *certificateV3) Version() Version {
|
||||
return Version3
|
||||
}
|
||||
|
||||
func (c *certificateV3) Curve() Curve {
|
||||
return c.v2.curve
|
||||
}
|
||||
|
||||
func (c *certificateV3) Groups() []string {
|
||||
return c.v2.details.groups
|
||||
}
|
||||
|
||||
func (c *certificateV3) IsCA() bool {
|
||||
return c.v2.details.isCA
|
||||
}
|
||||
|
||||
func (c *certificateV3) Issuer() string {
|
||||
return c.v2.details.issuer
|
||||
}
|
||||
|
||||
func (c *certificateV3) Name() string {
|
||||
return c.v2.details.name
|
||||
}
|
||||
|
||||
func (c *certificateV3) Networks() []netip.Prefix {
|
||||
return c.v2.details.networks
|
||||
}
|
||||
|
||||
func (c *certificateV3) NotAfter() time.Time {
|
||||
return c.v2.details.notAfter
|
||||
}
|
||||
|
||||
func (c *certificateV3) NotBefore() time.Time {
|
||||
return c.v2.details.notBefore
|
||||
}
|
||||
|
||||
// PublicKey returns the composite public key, classical || post-quantum.
|
||||
func (c *certificateV3) PublicKey() []byte {
|
||||
k := make([]byte, 0, len(c.v2.publicKey)+len(c.pqPublicKey))
|
||||
k = append(k, c.v2.publicKey...)
|
||||
return append(k, c.pqPublicKey...)
|
||||
}
|
||||
|
||||
func (c *certificateV3) MarshalPublicKeyPEM() []byte {
|
||||
return marshalCertPublicKeyToPEM(c)
|
||||
}
|
||||
|
||||
// Signature returns the classical signature. The post-quantum signature covers it.
|
||||
func (c *certificateV3) Signature() []byte {
|
||||
return c.v2.signature
|
||||
}
|
||||
|
||||
func (c *certificateV3) UnsafeNetworks() []netip.Prefix {
|
||||
return c.v2.details.unsafeNetworks
|
||||
}
|
||||
|
||||
// Fingerprint is the sha256 of the whole certificate. It differs from the fingerprint of the v2 form.
|
||||
func (c *certificateV3) Fingerprint() (string, error) {
|
||||
b, err := c.Marshal()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
// CheckSignature checks both signatures against the composite public key of the signing CA. Like the classical
|
||||
// signature with the curve, the post-quantum signature is checked with the algorithm of this certificate's suite,
|
||||
// which the signing CA has to share.
|
||||
func (c *certificateV3) CheckSignature(key []byte) bool {
|
||||
p := pqSuites[c.pqSuite]
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
classical, pq, err := c.pqSuite.SplitPublicKey(true, key)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if !c.v2.CheckSignature(classical) {
|
||||
return false
|
||||
}
|
||||
b, err := c.marshalForPQSigning()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return p.dsa.verify(pq, b, c.pqSignature)
|
||||
}
|
||||
|
||||
func (c *certificateV3) Expired(t time.Time) bool {
|
||||
return c.v2.Expired(t)
|
||||
}
|
||||
|
||||
// VerifyPrivateKey checks a composite private key, classical || post-quantum seed, against the composite public key.
|
||||
func (c *certificateV3) VerifyPrivateKey(curve Curve, key []byte) error {
|
||||
classical, seed, err := c.pqSuite.SplitPrivateKey(c.IsCA(), key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.v2.VerifyPrivateKey(curve, classical); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
pub, err := c.pqSuite.publicKey(c.IsCA(), seed)
|
||||
if err != nil {
|
||||
return ErrInvalidPrivateKey
|
||||
}
|
||||
if !bytes.Equal(pub, c.pqPublicKey) {
|
||||
return ErrPublicPrivateKeyMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *certificateV3) String() string {
|
||||
mb, err := c.marshalJSON()
|
||||
if err != nil {
|
||||
return fmt.Sprintf("<error marshalling certificate: %v>", err)
|
||||
}
|
||||
|
||||
b, err := json.MarshalIndent(mb, "", "\t")
|
||||
if err != nil {
|
||||
return fmt.Sprintf("<error marshalling certificate: %v>", err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// MarshalForHandshakes leaves out both public keys, the handshake carries them as the composite static key. It keeps
|
||||
// the suite, which says how to split that key.
|
||||
func (c *certificateV3) MarshalForHandshakes() ([]byte, error) {
|
||||
return c.marshal(false, false)
|
||||
}
|
||||
|
||||
func (c *certificateV3) Marshal() ([]byte, error) {
|
||||
return c.marshal(true, false)
|
||||
}
|
||||
|
||||
// marshalForPQSigning returns the bytes the post-quantum signature covers: every field but that signature, with the
|
||||
// curve always present. The suite is always present anyway.
|
||||
func (c *certificateV3) marshalForPQSigning() ([]byte, error) {
|
||||
return c.marshal(true, true)
|
||||
}
|
||||
|
||||
func (c *certificateV3) marshal(withPublicKeys, forSigning bool) ([]byte, error) {
|
||||
if c.v2.rawDetails == nil {
|
||||
return nil, ErrEmptyRawDetails
|
||||
}
|
||||
var b cryptobyte.Builder
|
||||
b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes(c.v2.rawDetails)
|
||||
|
||||
if withPublicKeys {
|
||||
if forSigning || c.v2.curve != Curve_CURVE25519 {
|
||||
b.AddASN1(TagCertCurve, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes([]byte{byte(c.v2.curve)})
|
||||
})
|
||||
}
|
||||
b.AddASN1(TagCertPublicKey, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes(c.v2.publicKey)
|
||||
})
|
||||
}
|
||||
|
||||
b.AddASN1(TagCertSignature, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes(c.v2.signature)
|
||||
})
|
||||
|
||||
b.AddASN1(TagCertPQSuite, func(b *cryptobyte.Builder) {
|
||||
b.AddUint8(uint8(c.pqSuite))
|
||||
})
|
||||
|
||||
if withPublicKeys {
|
||||
b.AddASN1(TagCertPQPublicKey, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes(c.pqPublicKey)
|
||||
})
|
||||
}
|
||||
|
||||
if !forSigning {
|
||||
b.AddASN1(TagCertPQSignature, func(b *cryptobyte.Builder) {
|
||||
b.AddBytes(c.pqSignature)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
func (c *certificateV3) MarshalPEM() ([]byte, error) {
|
||||
b, err := c.Marshal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: CertificateV3Banner, Bytes: b}), nil
|
||||
}
|
||||
|
||||
func (c *certificateV3) MarshalJSON() ([]byte, error) {
|
||||
b, err := c.marshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(b)
|
||||
}
|
||||
|
||||
func (c *certificateV3) marshalJSON() (m, error) {
|
||||
mb, err := c.v2.marshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fp, err := c.Fingerprint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mb["v2Fingerprint"] = mb["fingerprint"]
|
||||
mb["fingerprint"] = fp
|
||||
mb["version"] = Version3
|
||||
mb["pqSuite"] = c.pqSuite.String()
|
||||
mb["pqPublicKey"] = fmt.Sprintf("%x", c.pqPublicKey)
|
||||
mb["pqSignature"] = fmt.Sprintf("%x", c.pqSignature)
|
||||
return mb, nil
|
||||
}
|
||||
|
||||
func (c *certificateV3) Copy() Certificate {
|
||||
nc := &certificateV3{
|
||||
v2: *c.v2.Copy().(*certificateV2),
|
||||
pqSuite: c.pqSuite,
|
||||
pqPublicKey: make([]byte, len(c.pqPublicKey)),
|
||||
pqSignature: make([]byte, len(c.pqSignature)),
|
||||
}
|
||||
copy(nc.pqPublicKey, c.pqPublicKey)
|
||||
copy(nc.pqSignature, c.pqSignature)
|
||||
return nc
|
||||
}
|
||||
|
||||
func (c *certificateV3) validate() error {
|
||||
if err := c.v2.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !c.pqSuite.Valid() {
|
||||
return fmt.Errorf("%w: %v", ErrUnknownPQSuite, c.pqSuite)
|
||||
}
|
||||
if !c.pqSuite.checkPublicKey(c.IsCA(), c.pqPublicKey) {
|
||||
return ErrInvalidPublicKey
|
||||
}
|
||||
|
||||
if len(c.pqSignature) != c.pqSuite.signatureSize() {
|
||||
return ErrBadFormat
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unmarshalCertificateV3 parses a v3 certificate. publicKey is the composite public key when the certificate came
|
||||
// from a handshake, which then must not carry either public key itself.
|
||||
func unmarshalCertificateV3(b []byte, publicKey []byte, curve Curve) (*certificateV3, error) {
|
||||
l := len(b)
|
||||
if l == 0 || l > MaxCertificateSize {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
input := cryptobyte.String(b)
|
||||
var body cryptobyte.String
|
||||
if !input.ReadASN1(&body, asn1.SEQUENCE) || body.Empty() || !input.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
var rawDetails cryptobyte.String
|
||||
if !body.ReadASN1Element(&rawDetails, TagCertDetails) || rawDetails.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
var rawCurve byte
|
||||
if !readOptionalASN1Byte(&body, &rawCurve, TagCertCurve, byte(curve)) {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
curve = Curve(rawCurve)
|
||||
|
||||
fromHandshake := len(publicKey) > 0
|
||||
var classical, pq cryptobyte.String
|
||||
if fromHandshake {
|
||||
if body.PeekASN1Tag(TagCertPublicKey) {
|
||||
return nil, ErrCertPubkeyPresent
|
||||
}
|
||||
} else if !body.ReadASN1(&classical, TagCertPublicKey) || classical.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
var signature cryptobyte.String
|
||||
if !body.ReadASN1(&signature, TagCertSignature) || signature.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
var rawSuite cryptobyte.String
|
||||
if !body.ReadASN1(&rawSuite, TagCertPQSuite) || len(rawSuite) != 1 {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
suite := PQSuite(rawSuite[0])
|
||||
if !suite.Valid() {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, suite)
|
||||
}
|
||||
|
||||
if fromHandshake {
|
||||
if body.PeekASN1Tag(TagCertPQPublicKey) {
|
||||
return nil, ErrCertPubkeyPresent
|
||||
}
|
||||
} else if !body.ReadASN1(&pq, TagCertPQPublicKey) || pq.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
var pqSignature cryptobyte.String
|
||||
if !body.ReadASN1(&pqSignature, TagCertPQSignature) || pqSignature.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
if !body.Empty() {
|
||||
return nil, ErrBadFormat
|
||||
}
|
||||
|
||||
details, err := unmarshalDetails(rawDetails)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if fromHandshake {
|
||||
k, p, err := suite.SplitPublicKey(details.isCA, publicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
classical = bytes.Clone(k)
|
||||
pq = bytes.Clone(p)
|
||||
}
|
||||
|
||||
c := &certificateV3{
|
||||
v2: certificateV2{
|
||||
details: details,
|
||||
rawDetails: rawDetails,
|
||||
curve: curve,
|
||||
publicKey: classical,
|
||||
signature: signature,
|
||||
},
|
||||
pqSuite: suite,
|
||||
pqPublicKey: pq,
|
||||
pqSignature: pqSignature,
|
||||
}
|
||||
|
||||
if err := c.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ExtendToV3 builds the version 3 certificate in suite that extends the version 2 certificate c with pqPublicKey, the
|
||||
// composite public key's post-quantum half. pqSign produces the suite's post-quantum signature, see SignPQ.
|
||||
//
|
||||
// A CA certificate signs its own extension: signer must be nil and pqSign must use the private key for pqPublicKey.
|
||||
// A host certificate is extended by its issuing CA: signer is the v3 form of that CA, which must be in the same suite.
|
||||
// In both cases c's classical signature, and so its fingerprint, are left unchanged, so certificates in use can be
|
||||
// extended in place.
|
||||
func ExtendToV3(c Certificate, suite PQSuite, pqPublicKey []byte, signer Certificate, pqSign SignerLambda) (Certificate, error) {
|
||||
c2, ok := c.(*certificateV2)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("only version 2 certificates can be extended to version 3, got version %d", c.Version())
|
||||
}
|
||||
if !suite.Valid() {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, suite)
|
||||
}
|
||||
|
||||
var signingKey []byte
|
||||
if c2.IsCA() {
|
||||
if signer != nil {
|
||||
return nil, fmt.Errorf("a CA certificate must extend itself, signer must be nil")
|
||||
}
|
||||
if !c2.CheckSignature(c2.publicKey) {
|
||||
return nil, ErrNotSelfSigned
|
||||
}
|
||||
signingKey = append(bytes.Clone(c2.publicKey), pqPublicKey...)
|
||||
} else {
|
||||
if signer == nil || signer.Version() != Version3 || !signer.IsCA() {
|
||||
return nil, fmt.Errorf("a host certificate must be extended by a version 3 CA")
|
||||
}
|
||||
if PQSuiteOf(signer) != suite {
|
||||
return nil, ErrPQSuiteMismatch
|
||||
}
|
||||
signerV2 := V2Form(signer)
|
||||
issuer, err := signerV2.Fingerprint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c2.Issuer() != issuer {
|
||||
return nil, fmt.Errorf("certificate was not issued by the signing CA")
|
||||
}
|
||||
if !c2.CheckSignature(signerV2.PublicKey()) {
|
||||
return nil, ErrSignatureMismatch
|
||||
}
|
||||
signingKey = signer.PublicKey()
|
||||
}
|
||||
|
||||
c3 := &certificateV3{
|
||||
v2: *c2.Copy().(*certificateV2),
|
||||
pqSuite: suite,
|
||||
pqPublicKey: bytes.Clone(pqPublicKey),
|
||||
}
|
||||
if len(c3.pqPublicKey) != suite.PublicKeySize(c3.IsCA()) {
|
||||
return nil, ErrInvalidPublicKey
|
||||
}
|
||||
|
||||
b, err := c3.marshalForPQSigning()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sig, err := pqSign(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c3.pqSignature = sig
|
||||
|
||||
if err := c3.validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Catch a pqSign that used the wrong key before the certificate goes anywhere.
|
||||
if !c3.CheckSignature(signingKey) {
|
||||
return nil, ErrSignatureMismatch
|
||||
}
|
||||
|
||||
return c3, nil
|
||||
}
|
||||
|
||||
// SignPQ returns a SignerLambda that signs certificates with the private key seed of suite's signature algorithm.
|
||||
// Signatures are deterministic, so signing the same certificate twice gives the same bytes and the same fingerprint,
|
||||
// and extending a certificate is idempotent.
|
||||
func SignPQ(suite PQSuite, seed []byte) (SignerLambda, error) {
|
||||
p := pqSuites[suite]
|
||||
if p == nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, suite)
|
||||
}
|
||||
if len(seed) != p.dsa.privateKeySize {
|
||||
return nil, ErrInvalidPrivateKey
|
||||
}
|
||||
return p.dsa.signer(seed)
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/mldsa"
|
||||
"crypto/mlkem"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert/p256"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/cryptobyte"
|
||||
"golang.org/x/crypto/cryptobyte/asn1"
|
||||
)
|
||||
|
||||
var testCurves = []Curve{Curve_CURVE25519, Curve_P256}
|
||||
|
||||
func newTestV3(t *testing.T, curve Curve) (ca Certificate, caKey []byte, host Certificate, hostKey []byte) {
|
||||
t.Helper()
|
||||
ca, _, caKey, _ = NewTestCaCert(Version3, curve, time.Time{}, time.Time{}, nil, nil, []string{"g"})
|
||||
host, _, hostKeyPEM, _ := NewTestCert(Version3, curve, ca, caKey, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")}, nil, []string{"g"})
|
||||
hostKey, _, _, err := UnmarshalPrivateKeyFromPEM(hostKeyPEM)
|
||||
require.NoError(t, err)
|
||||
return ca, caKey, host, hostKey
|
||||
}
|
||||
|
||||
func TestCertificateV3_Sign(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, caKey, host, hostKey := newTestV3(t, curve)
|
||||
assert.Equal(t, Version3, ca.Version())
|
||||
assert.Equal(t, Version3, host.Version())
|
||||
|
||||
assert.True(t, ca.CheckSignature(ca.PublicKey()))
|
||||
assert.True(t, host.CheckSignature(ca.PublicKey()))
|
||||
require.NoError(t, ca.VerifyPrivateKey(curve, caKey))
|
||||
require.NoError(t, host.VerifyPrivateKey(curve, hostKey))
|
||||
|
||||
// The classical half of the key alone is not the key.
|
||||
require.Error(t, host.VerifyPrivateKey(curve, hostKey[:len(hostKey)-MLKEM1024PrivateKeySize]))
|
||||
|
||||
// The issuer is the v2 form of the CA, which old peers know it by.
|
||||
caV2Fp, err := V2Form(ca).Fingerprint()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, caV2Fp, host.Issuer())
|
||||
|
||||
// A v2 CA can not sign a v3 certificate, nor a v3 CA a v2 one.
|
||||
_, err = (&TBSCertificate{Version: Version3, Curve: curve, PQSuite: DefaultPQSuite, Name: "x", Networks: host.Networks(), NotBefore: host.NotBefore(), NotAfter: host.NotAfter(), PublicKey: host.PublicKey()}).Sign(V2Form(ca), curve, caKey)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The v2 form must be exactly the certificate the CA's v2 form would have signed, so peers that only speak v2
|
||||
// accept it. Ed25519 signatures are deterministic, so the bytes can be compared outright.
|
||||
func TestCertificateV3_V2FormIsExact(t *testing.T) {
|
||||
ca, caKey, host, _ := newTestV3(t, Curve_CURVE25519)
|
||||
classicalCAKey := caKey[:len(caKey)-MLDSA87PrivateKeySize]
|
||||
classicalPub := V2Form(host).PublicKey()
|
||||
|
||||
tbs := &TBSCertificate{
|
||||
Version: Version2,
|
||||
Curve: Curve_CURVE25519,
|
||||
Name: host.Name(),
|
||||
Networks: host.Networks(),
|
||||
Groups: host.Groups(),
|
||||
NotBefore: host.NotBefore(),
|
||||
NotAfter: host.NotAfter(),
|
||||
PublicKey: classicalPub,
|
||||
}
|
||||
v2, err := tbs.Sign(V2Form(ca), Curve_CURVE25519, classicalCAKey)
|
||||
require.NoError(t, err)
|
||||
|
||||
want, err := v2.Marshal()
|
||||
require.NoError(t, err)
|
||||
got, err := V2Form(host).Marshal()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, want, got)
|
||||
|
||||
wantHS, err := v2.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
gotHS, err := V2Form(host).MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, wantHS, gotHS)
|
||||
|
||||
assert.Nil(t, V2Form(v2))
|
||||
}
|
||||
|
||||
func TestCertificateV3_MarshalRoundTrip(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, _, host, _ := newTestV3(t, curve)
|
||||
|
||||
for _, c := range []Certificate{ca, host} {
|
||||
b, err := c.Marshal()
|
||||
require.NoError(t, err)
|
||||
c2, err := unmarshalCertificateV3(b, nil, Curve_CURVE25519)
|
||||
require.NoError(t, err)
|
||||
assertCertsEqual(t, c, c2)
|
||||
|
||||
p, err := c.MarshalPEM()
|
||||
require.NoError(t, err)
|
||||
c3, rest, err := UnmarshalCertificateFromPEM(p)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, rest)
|
||||
assertCertsEqual(t, c, c3)
|
||||
|
||||
// Handshakes carry the composite public key in the noise static, not in the certificate.
|
||||
hs, err := c.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
assert.Less(t, len(hs), len(b)-len(c.PublicKey()))
|
||||
c4, err := Recombine(Version3, hs, c.PublicKey(), curve)
|
||||
require.NoError(t, err)
|
||||
assertCertsEqual(t, c, c4)
|
||||
|
||||
_, err = Recombine(Version3, b, c.PublicKey(), curve)
|
||||
require.ErrorIs(t, err, ErrCertPubkeyPresent)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertCertsEqual(t *testing.T, want, got Certificate) {
|
||||
t.Helper()
|
||||
wb, err := want.Marshal()
|
||||
require.NoError(t, err)
|
||||
gb, err := got.Marshal()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, wb, gb)
|
||||
wf, err := want.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
gf, err := got.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, wf, gf)
|
||||
assert.Equal(t, want.PublicKey(), got.PublicKey())
|
||||
}
|
||||
|
||||
// rebuildV3 re-encodes a v3 certificate's envelope after edit has had a go at its fields.
|
||||
func rebuildV3(t *testing.T, c Certificate, edit func(fields map[asn1.Tag][]byte, order *[]asn1.Tag)) []byte {
|
||||
t.Helper()
|
||||
b, err := c.Marshal()
|
||||
require.NoError(t, err)
|
||||
in := cryptobyte.String(b)
|
||||
var body cryptobyte.String
|
||||
require.True(t, in.ReadASN1(&body, asn1.SEQUENCE))
|
||||
|
||||
fields := map[asn1.Tag][]byte{}
|
||||
var order []asn1.Tag
|
||||
for !body.Empty() {
|
||||
var el cryptobyte.String
|
||||
var tag asn1.Tag
|
||||
require.True(t, body.ReadAnyASN1Element(&el, &tag))
|
||||
fields[tag] = el
|
||||
order = append(order, tag)
|
||||
}
|
||||
edit(fields, &order)
|
||||
|
||||
var out cryptobyte.Builder
|
||||
out.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
|
||||
for _, tag := range order {
|
||||
b.AddBytes(fields[tag])
|
||||
}
|
||||
})
|
||||
return out.BytesOrPanic()
|
||||
}
|
||||
|
||||
func TestCertificateV3_StrictParse(t *testing.T) {
|
||||
_, _, host, _ := newTestV3(t, Curve_CURVE25519)
|
||||
good, err := host.Marshal()
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = unmarshalCertificateV3(append(good, 0), nil, Curve_CURVE25519)
|
||||
require.ErrorIs(t, err, ErrBadFormat, "trailing bytes after the envelope")
|
||||
|
||||
trailing := rebuildV3(t, host, func(fields map[asn1.Tag][]byte, order *[]asn1.Tag) {
|
||||
fields[7|classContextSpecific] = []byte{7 | classContextSpecific, 1, 0}
|
||||
*order = append(*order, 7|classContextSpecific)
|
||||
})
|
||||
_, err = unmarshalCertificateV3(trailing, nil, Curve_CURVE25519)
|
||||
require.ErrorIs(t, err, ErrBadFormat, "unknown field after the pq signature")
|
||||
|
||||
for _, tag := range []asn1.Tag{TagCertPQSuite, TagCertPQPublicKey, TagCertPQSignature} {
|
||||
missing := rebuildV3(t, host, func(fields map[asn1.Tag][]byte, order *[]asn1.Tag) {
|
||||
*order = removeTag(*order, tag)
|
||||
})
|
||||
_, err = unmarshalCertificateV3(missing, nil, Curve_CURVE25519)
|
||||
require.Error(t, err, "missing %x", tag)
|
||||
}
|
||||
|
||||
// A v2 certificate is not a v3 one.
|
||||
v2, err := V2Form(host).Marshal()
|
||||
require.NoError(t, err)
|
||||
_, err = unmarshalCertificateV3(v2, nil, Curve_CURVE25519)
|
||||
require.Error(t, err)
|
||||
|
||||
// A wrong sized post-quantum key fails validation.
|
||||
short := rebuildV3(t, host, func(fields map[asn1.Tag][]byte, order *[]asn1.Tag) {
|
||||
var b cryptobyte.Builder
|
||||
b.AddASN1(TagCertPQPublicKey, func(b *cryptobyte.Builder) { b.AddBytes(make([]byte, MLKEM1024PublicKeySize-1)) })
|
||||
fields[TagCertPQPublicKey] = b.BytesOrPanic()
|
||||
})
|
||||
_, err = unmarshalCertificateV3(short, nil, Curve_CURVE25519)
|
||||
require.ErrorIs(t, err, ErrInvalidPublicKey)
|
||||
|
||||
// The suite is one known value, PQSuiteUnknown included in what is not.
|
||||
for _, suite := range [][]byte{{byte(PQSuiteUnknown)}, {200}, {}, {1, 1}} {
|
||||
bad := rebuildV3(t, host, func(fields map[asn1.Tag][]byte, order *[]asn1.Tag) {
|
||||
var b cryptobyte.Builder
|
||||
b.AddASN1(TagCertPQSuite, func(b *cryptobyte.Builder) { b.AddBytes(suite) })
|
||||
fields[TagCertPQSuite] = b.BytesOrPanic()
|
||||
})
|
||||
_, err = unmarshalCertificateV3(bad, nil, Curve_CURVE25519)
|
||||
require.Error(t, err, "suite %x", suite)
|
||||
}
|
||||
}
|
||||
|
||||
func removeTag(order []asn1.Tag, tag asn1.Tag) []asn1.Tag {
|
||||
var out []asn1.Tag
|
||||
for _, t := range order {
|
||||
if t != tag {
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestCertificateV3_Tamper(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, _, host, _ := newTestV3(t, curve)
|
||||
|
||||
// Swapping the post-quantum key breaks only the post-quantum signature, which must still catch it.
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
swapped := host.Copy().(*certificateV3)
|
||||
swapped.pqPublicKey = dk.EncapsulationKey().Bytes()
|
||||
assert.True(t, V2Form(swapped).CheckSignature(V2Form(ca).PublicKey()))
|
||||
assert.False(t, swapped.CheckSignature(ca.PublicKey()))
|
||||
|
||||
// The post-quantum signature covers the classical one.
|
||||
resigned := host.Copy().(*certificateV3)
|
||||
if curve == Curve_P256 {
|
||||
sig, err := p256.Swap(resigned.v2.signature)
|
||||
require.NoError(t, err)
|
||||
resigned.v2.signature = sig
|
||||
assert.True(t, V2Form(resigned).CheckSignature(V2Form(ca).PublicKey()))
|
||||
} else {
|
||||
resigned.v2.signature[0] ^= 1
|
||||
}
|
||||
assert.False(t, resigned.CheckSignature(ca.PublicKey()))
|
||||
|
||||
// Another CA's post-quantum key does not verify.
|
||||
other, _, _, _ := NewTestCaCert(Version3, curve, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
k := append(V2Form(ca).PublicKey(), other.PublicKey()[len(V2Form(other).PublicKey()):]...)
|
||||
assert.False(t, host.CheckSignature(k))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCAPool_V3(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, _, host, _ := newTestV3(t, curve)
|
||||
now := time.Now()
|
||||
|
||||
// A v3 CA verifies v3 certificates, and only those.
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
cc, err := pool.VerifyCertificate(now, host)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, pool.VerifyCachedCertificate(now, cc))
|
||||
_, err = pool.VerifyCertificate(now, V2Form(host))
|
||||
require.ErrorIs(t, err, ErrCaNotFound)
|
||||
|
||||
// Listing the v2 form of the CA as well accepts the v2 form of the certificate.
|
||||
require.NoError(t, pool.AddCA(V2Form(ca)))
|
||||
_, err = pool.VerifyCertificate(now, V2Form(host))
|
||||
require.NoError(t, err)
|
||||
_, err = pool.VerifyCertificate(now, host)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The v2 form of the CA alone does not verify a v3 certificate.
|
||||
v2Pool := NewCAPool()
|
||||
require.NoError(t, v2Pool.AddCA(V2Form(ca)))
|
||||
_, err = v2Pool.VerifyCertificate(now, host)
|
||||
require.ErrorIs(t, err, ErrCaNotFound)
|
||||
|
||||
// A second v3 extension of the same v2 CA is ambiguous.
|
||||
sk, err := mldsa.GenerateKey(mldsa.MLDSA87())
|
||||
require.NoError(t, err)
|
||||
signPQ, err := SignPQ(DefaultPQSuite, sk.Bytes())
|
||||
require.NoError(t, err)
|
||||
again, err := ExtendToV3(V2Form(ca), DefaultPQSuite, sk.PublicKey().Bytes(), nil, signPQ)
|
||||
require.NoError(t, err)
|
||||
require.ErrorContains(t, pool.AddCA(again), "two version 3 CAs extend the same version 2 CA")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCAPool_V3Blocklist(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, _, host, _ := newTestV3(t, curve)
|
||||
now := time.Now()
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
require.NoError(t, pool.AddCA(V2Form(ca)))
|
||||
cc, err := pool.VerifyCertificate(now, host)
|
||||
require.NoError(t, err)
|
||||
|
||||
fp, err := host.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
v2Fp, err := V2Form(host).Fingerprint()
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, fp, v2Fp)
|
||||
|
||||
// Blocking the v3 fingerprint leaves the v2 form alone, which is why operators list both.
|
||||
pool.BlocklistFingerprint(fp)
|
||||
_, err = pool.VerifyCertificate(now, host)
|
||||
require.ErrorIs(t, err, ErrBlockListed)
|
||||
require.ErrorIs(t, pool.VerifyCachedCertificate(now, cc), ErrBlockListed)
|
||||
_, err = pool.VerifyCertificate(now, V2Form(host))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Blocking the v2 fingerprint blocks both.
|
||||
pool.ResetCertBlocklist()
|
||||
pool.BlocklistFingerprint(v2Fp)
|
||||
_, err = pool.VerifyCertificate(now, host)
|
||||
require.ErrorIs(t, err, ErrBlockListed)
|
||||
require.ErrorIs(t, pool.VerifyCachedCertificate(now, cc), ErrBlockListed)
|
||||
_, err = pool.VerifyCertificate(now, V2Form(host))
|
||||
require.ErrorIs(t, err, ErrBlockListed)
|
||||
|
||||
if curve == Curve_P256 {
|
||||
// So does the other form of a P256 v2 signature.
|
||||
alt, err := CalculateAlternateFingerprint(V2Form(host))
|
||||
require.NoError(t, err)
|
||||
pool.ResetCertBlocklist()
|
||||
pool.BlocklistFingerprint(alt)
|
||||
_, err = pool.VerifyCertificate(now, host)
|
||||
require.ErrorIs(t, err, ErrBlockListed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Certificates already in use extend in place: their v2 forms, and fingerprints, do not change.
|
||||
func TestExtendToV3(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca2, _, caKey2, _ := NewTestCaCert(Version2, curve, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
host2, _, _, _ := NewTestCert(Version2, curve, ca2, caKey2, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")}, nil, nil)
|
||||
|
||||
sk, err := mldsa.GenerateKey(mldsa.MLDSA87())
|
||||
require.NoError(t, err)
|
||||
signPQ, err := SignPQ(DefaultPQSuite, sk.Bytes())
|
||||
require.NoError(t, err)
|
||||
|
||||
ca3, err := ExtendToV3(ca2, DefaultPQSuite, sk.PublicKey().Bytes(), nil, signPQ)
|
||||
require.NoError(t, err)
|
||||
assertCertsEqual(t, ca2, V2Form(ca3))
|
||||
require.NoError(t, ca3.VerifyPrivateKey(curve, append(caKey2, sk.Bytes()...)))
|
||||
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
host3, err := ExtendToV3(host2, DefaultPQSuite, dk.EncapsulationKey().Bytes(), ca3, signPQ)
|
||||
require.NoError(t, err)
|
||||
assertCertsEqual(t, host2, V2Form(host3))
|
||||
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca3))
|
||||
_, err = pool.VerifyCertificate(time.Now(), host3)
|
||||
require.NoError(t, err)
|
||||
|
||||
// A host must be extended by its own issuer, and with that issuer's key.
|
||||
other2, _, _, _ := NewTestCaCert(Version2, curve, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
other3, err := ExtendToV3(other2, DefaultPQSuite, sk.PublicKey().Bytes(), nil, signPQ)
|
||||
require.NoError(t, err)
|
||||
_, err = ExtendToV3(host2, DefaultPQSuite, dk.EncapsulationKey().Bytes(), other3, signPQ)
|
||||
require.Error(t, err)
|
||||
|
||||
wrong, err := mldsa.GenerateKey(mldsa.MLDSA87())
|
||||
require.NoError(t, err)
|
||||
wrongSign, err := SignPQ(DefaultPQSuite, wrong.Bytes())
|
||||
require.NoError(t, err)
|
||||
_, err = ExtendToV3(host2, DefaultPQSuite, dk.EncapsulationKey().Bytes(), ca3, wrongSign)
|
||||
require.ErrorIs(t, err, ErrSignatureMismatch)
|
||||
|
||||
// A CA extends itself, and needs its own post-quantum key to.
|
||||
_, err = ExtendToV3(ca2, DefaultPQSuite, sk.PublicKey().Bytes(), nil, wrongSign)
|
||||
require.ErrorIs(t, err, ErrSignatureMismatch)
|
||||
_, err = ExtendToV3(ca2, DefaultPQSuite, sk.PublicKey().Bytes(), ca3, signPQ)
|
||||
require.Error(t, err)
|
||||
|
||||
// Only v2 certificates extend.
|
||||
_, err = ExtendToV3(host3, DefaultPQSuite, dk.EncapsulationKey().Bytes(), ca3, signPQ)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ML-DSA-87 signing is deterministic, so extending a certificate twice gives the same bytes and the same fingerprint:
|
||||
// pq-extend is idempotent, and a CA extended again is not a second v3 CA to the pool.
|
||||
func TestExtendToV3_Deterministic(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca2, _, caKey2, _ := NewTestCaCert(Version2, curve, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
host2, _, _, _ := NewTestCert(Version2, curve, ca2, caKey2, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")}, nil, nil)
|
||||
sk, err := mldsa.GenerateKey(mldsa.MLDSA87())
|
||||
require.NoError(t, err)
|
||||
signPQ, err := SignPQ(DefaultPQSuite, sk.Bytes())
|
||||
require.NoError(t, err)
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
|
||||
extend := func(c Certificate, pq []byte, signer Certificate) ([]byte, string, Certificate) {
|
||||
c3, err := ExtendToV3(c, DefaultPQSuite, pq, signer, signPQ)
|
||||
require.NoError(t, err)
|
||||
b, err := c3.Marshal()
|
||||
require.NoError(t, err)
|
||||
fp, err := c3.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
return b, fp, c3
|
||||
}
|
||||
|
||||
caBytesA, caFpA, caA := extend(ca2, sk.PublicKey().Bytes(), nil)
|
||||
caBytesB, caFpB, caB := extend(ca2, sk.PublicKey().Bytes(), nil)
|
||||
assert.Equal(t, caBytesA, caBytesB)
|
||||
assert.Equal(t, caFpA, caFpB)
|
||||
|
||||
hostBytesA, hostFpA, _ := extend(host2, dk.EncapsulationKey().Bytes(), caA)
|
||||
hostBytesB, hostFpB, _ := extend(host2, dk.EncapsulationKey().Bytes(), caB)
|
||||
assert.Equal(t, hostBytesA, hostBytesB)
|
||||
assert.Equal(t, hostFpA, hostFpB)
|
||||
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(caA))
|
||||
require.NoError(t, pool.AddCA(caB))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateV3_KeyPEM(t *testing.T) {
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, caKey, host, hostKey := newTestV3(t, curve)
|
||||
|
||||
pub, rest, gotCurve, err := UnmarshalPublicKeyFromPEM(host.MarshalPublicKeyPEM())
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, rest)
|
||||
assert.Equal(t, curve, gotCurve)
|
||||
assert.Equal(t, host.PublicKey(), pub)
|
||||
|
||||
pub, _, gotCurve, err = UnmarshalSigningPublicKeyFromPEM(ca.MarshalPublicKeyPEM())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, curve, gotCurve)
|
||||
assert.Equal(t, ca.PublicKey(), pub)
|
||||
|
||||
key, _, gotCurve, err := UnmarshalPrivateKeyFromPEM(MarshalPQPrivateKeyToPEM(curve, DefaultPQSuite, hostKey))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, curve, gotCurve)
|
||||
assert.Equal(t, hostKey, key)
|
||||
|
||||
key, _, gotCurve, err = UnmarshalSigningPrivateKeyFromPEM(MarshalPQSigningPrivateKeyToPEM(curve, DefaultPQSuite, caKey))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, curve, gotCurve)
|
||||
assert.Equal(t, caKey, key)
|
||||
|
||||
kdf := NewArgon2Parameters(64*1024, 4, 1)
|
||||
enc, err := EncryptAndMarshalPQSigningPrivateKey(curve, DefaultPQSuite, caKey, []byte("pw"), kdf)
|
||||
require.NoError(t, err)
|
||||
_, _, _, err = UnmarshalSigningPrivateKeyFromPEM(enc)
|
||||
require.ErrorIs(t, err, ErrPrivateKeyEncrypted)
|
||||
gotCurve, key, _, err = DecryptAndUnmarshalSigningPrivateKey([]byte("pw"), enc)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, curve, gotCurve)
|
||||
assert.Equal(t, caKey, key)
|
||||
|
||||
// The banners name both halves.
|
||||
assert.Contains(t, string(MarshalPQPrivateKeyToPEM(curve, DefaultPQSuite, hostKey)), " MLKEM1024 PRIVATE KEY-----")
|
||||
assert.Contains(t, string(MarshalPQSigningPrivateKeyToPEM(curve, DefaultPQSuite, caKey)), " MLDSA87 PRIVATE KEY-----")
|
||||
assert.Contains(t, string(enc), " MLDSA87 ENCRYPTED PRIVATE KEY-----")
|
||||
|
||||
// A key of the wrong size, or for an unknown suite, has no banner.
|
||||
assert.Nil(t, MarshalPQPrivateKeyToPEM(curve, DefaultPQSuite, hostKey[1:]))
|
||||
assert.Nil(t, MarshalPQPrivateKeyToPEM(curve, PQSuiteUnknown, hostKey))
|
||||
assert.Nil(t, MarshalPQSigningPrivateKeyToPEM(curve, DefaultPQSuite, caKey[1:]))
|
||||
_, err = EncryptAndMarshalPQSigningPrivateKey(curve, DefaultPQSuite, caKey[1:], []byte("pw"), kdf)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
+43
-11
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -158,6 +159,33 @@ func splitNonceCiphertext(blob []byte, nonceSize int) ([]byte, []byte, error) {
|
||||
|
||||
// EncryptAndMarshalSigningPrivateKey is a simple helper to encrypt and PEM encode a private key
|
||||
func EncryptAndMarshalSigningPrivateKey(curve Curve, b []byte, passphrase []byte, kdfParams *Argon2Parameters) ([]byte, error) {
|
||||
switch curve {
|
||||
case Curve_CURVE25519:
|
||||
return encryptAndMarshalSigningPrivateKey(EncryptedEd25519PrivateKeyBanner, b, passphrase, kdfParams)
|
||||
case Curve_P256:
|
||||
return encryptAndMarshalSigningPrivateKey(EncryptedECDSAP256PrivateKeyBanner, b, passphrase, kdfParams)
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid curve: %v", curve)
|
||||
}
|
||||
}
|
||||
|
||||
// EncryptAndMarshalPQSigningPrivateKey encrypts and PEM encodes a composite CA private key of suite, the classical
|
||||
// signing key followed by the seed of the suite's signature algorithm.
|
||||
func EncryptAndMarshalPQSigningPrivateKey(curve Curve, suite PQSuite, b []byte, passphrase []byte, kdfParams *Argon2Parameters) ([]byte, error) {
|
||||
p := pqSuites[suite]
|
||||
if p == nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, suite)
|
||||
}
|
||||
if curve != Curve_CURVE25519 && curve != Curve_P256 {
|
||||
return nil, fmt.Errorf("invalid curve: %v", curve)
|
||||
}
|
||||
if len(b) != pqKeySize(pqSigningPrivateKey, curve, p) {
|
||||
return nil, ErrInvalidPrivateKey
|
||||
}
|
||||
return encryptAndMarshalSigningPrivateKey(pqBannerName(pqEncryptedSigningPrivateKey, curve, p), b, passphrase, kdfParams)
|
||||
}
|
||||
|
||||
func encryptAndMarshalSigningPrivateKey(banner string, b []byte, passphrase []byte, kdfParams *Argon2Parameters) ([]byte, error) {
|
||||
ciphertext, err := aes256Encrypt(passphrase, kdfParams, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -180,14 +208,7 @@ func EncryptAndMarshalSigningPrivateKey(curve Curve, b []byte, passphrase []byte
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch curve {
|
||||
case Curve_CURVE25519:
|
||||
return pem.EncodeToMemory(&pem.Block{Type: EncryptedEd25519PrivateKeyBanner, Bytes: b}), nil
|
||||
case Curve_P256:
|
||||
return pem.EncodeToMemory(&pem.Block{Type: EncryptedECDSAP256PrivateKeyBanner, Bytes: b}), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid curve: %v", curve)
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: banner, Bytes: b}), nil
|
||||
}
|
||||
|
||||
// UnmarshalNebulaEncryptedData will unmarshal a protobuf byte representation of a nebula cert into its
|
||||
@@ -260,10 +281,14 @@ func DecryptAndUnmarshalSigningPrivateKey(passphrase, b []byte) (Curve, []byte,
|
||||
return curve, nil, r, fmt.Errorf("input did not contain a valid PEM encoded block")
|
||||
}
|
||||
|
||||
switch k.Type {
|
||||
case EncryptedEd25519PrivateKeyBanner:
|
||||
pq, pqKey := pqKeyBanners[k.Type]
|
||||
pqKey = pqKey && pq.kind == pqEncryptedSigningPrivateKey
|
||||
switch {
|
||||
case pqKey:
|
||||
curve = pq.curve
|
||||
case k.Type == EncryptedEd25519PrivateKeyBanner:
|
||||
curve = Curve_CURVE25519
|
||||
case EncryptedECDSAP256PrivateKeyBanner:
|
||||
case k.Type == EncryptedECDSAP256PrivateKeyBanner:
|
||||
curve = Curve_P256
|
||||
default:
|
||||
return curve, nil, r, fmt.Errorf("bytes did not contain a proper nebula encrypted Ed25519/ECDSA private key banner")
|
||||
@@ -285,6 +310,13 @@ func DecryptAndUnmarshalSigningPrivateKey(passphrase, b []byte) (Curve, []byte,
|
||||
return curve, nil, r, fmt.Errorf("unsupported encryption algorithm: %s", ned.EncryptionMetadata.EncryptionAlgorithm)
|
||||
}
|
||||
|
||||
if pqKey {
|
||||
if len(bytes) != pq.size {
|
||||
return curve, nil, r, fmt.Errorf("key was not %d bytes, is invalid %s", pq.size, strings.ToLower(strings.TrimPrefix(k.Type, "NEBULA ")))
|
||||
}
|
||||
return curve, bytes, r, nil
|
||||
}
|
||||
|
||||
switch curve {
|
||||
case Curve_CURVE25519:
|
||||
if len(bytes) != ed25519.PrivateKeySize {
|
||||
|
||||
@@ -23,6 +23,8 @@ var (
|
||||
ErrUnknownVersion = errors.New("certificate version unrecognized")
|
||||
ErrCertPubkeyPresent = errors.New("certificate has unexpected pubkey present")
|
||||
ErrCurveMismatch = errors.New("certificate curve does not match CA")
|
||||
ErrPQSuiteMismatch = errors.New("certificate post-quantum suite does not match CA")
|
||||
ErrUnknownPQSuite = errors.New("unknown post-quantum suite")
|
||||
|
||||
ErrInvalidPEMBlock = errors.New("input did not contain a valid PEM encoded block")
|
||||
ErrInvalidPEMCertificateBanner = errors.New("bytes did not contain a proper certificate banner")
|
||||
|
||||
@@ -39,6 +39,10 @@ func NewTestCaCert(version Version, curve Curve, before, after time.Time, networ
|
||||
// There is no default to allow the underlying lib to respond with an error
|
||||
}
|
||||
|
||||
if version == Version3 {
|
||||
pub, priv = appendPQSigningKey(pub, priv)
|
||||
}
|
||||
|
||||
if before.IsZero() {
|
||||
before = testCertNow.Add(time.Second * -60)
|
||||
}
|
||||
@@ -58,6 +62,9 @@ func NewTestCaCert(version Version, curve Curve, before, after time.Time, networ
|
||||
Groups: groups,
|
||||
IsCA: true,
|
||||
}
|
||||
if version == Version3 {
|
||||
t.PQSuite = DefaultPQSuite
|
||||
}
|
||||
|
||||
c, err := t.Sign(nil, curve, priv)
|
||||
if err != nil {
|
||||
@@ -97,6 +104,10 @@ func NewTestCert(v Version, curve Curve, ca Certificate, key []byte, name string
|
||||
panic("unknown curve")
|
||||
}
|
||||
|
||||
if v == Version3 {
|
||||
pub, priv = appendPQKey(ca, pub, priv)
|
||||
}
|
||||
|
||||
nc := &TBSCertificate{
|
||||
Version: v,
|
||||
Curve: curve,
|
||||
@@ -108,6 +119,7 @@ func NewTestCert(v Version, curve Curve, ca Certificate, key []byte, name string
|
||||
NotAfter: time.Unix(after.Unix(), 0),
|
||||
PublicKey: pub,
|
||||
IsCA: false,
|
||||
PQSuite: PQSuiteOf(ca),
|
||||
}
|
||||
|
||||
c, err := nc.Sign(ca, ca.Curve(), key)
|
||||
@@ -120,9 +132,30 @@ func NewTestCert(v Version, curve Curve, ca Certificate, key []byte, name string
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if v == Version3 {
|
||||
return c, pub, MarshalPQPrivateKeyToPEM(curve, PQSuiteOf(ca), priv), pem
|
||||
}
|
||||
return c, pub, MarshalPrivateKeyToPEM(curve, priv), pem
|
||||
}
|
||||
|
||||
// appendPQSigningKey makes a classical CA keypair into a version 3 composite one with a fresh key of the default suite.
|
||||
func appendPQSigningKey(pub, priv []byte) ([]byte, []byte) {
|
||||
pqPub, pqPriv, err := DefaultPQSuite.GenerateKey(true)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...)
|
||||
}
|
||||
|
||||
// appendPQKey makes a classical host keypair into a version 3 composite one with a fresh key of the CA's suite.
|
||||
func appendPQKey(ca Certificate, pub, priv []byte) ([]byte, []byte) {
|
||||
pqPub, pqPriv, err := PQSuiteOf(ca).GenerateKey(false)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...)
|
||||
}
|
||||
|
||||
func X25519Keypair() ([]byte, []byte) {
|
||||
privkey := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
|
||||
|
||||
+165
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/ed25519"
|
||||
)
|
||||
@@ -64,6 +66,7 @@ func SplitPEM(data []byte, atEOF bool) (advance int, token []byte, err error) {
|
||||
const ( //cert banners
|
||||
CertificateBanner = "NEBULA CERTIFICATE"
|
||||
CertificateV2Banner = "NEBULA CERTIFICATE V2"
|
||||
CertificateV3Banner = "NEBULA CERTIFICATE V3"
|
||||
)
|
||||
|
||||
const ( //key-agreement-key banners
|
||||
@@ -73,6 +76,109 @@ const ( //key-agreement-key banners
|
||||
P256PublicKeyBanner = "NEBULA P256 PUBLIC KEY"
|
||||
)
|
||||
|
||||
// Version 3 keys are composite: the classical key followed by the post-quantum key of the certificate's PQSuite, a
|
||||
// KEM seed or public key for hosts and a signature algorithm's seed or public key for CAs. Their banners name both
|
||||
// halves, "NEBULA X25519 MLKEM1024 PRIVATE KEY" or "NEBULA ED25519 MLDSA87 PUBLIC KEY" for example, because the
|
||||
// post-quantum algorithm can not be told from the key's size: ML-KEM and ML-DSA seeds are the same size at every
|
||||
// strength. The banners name algorithms, not suites, so suites sharing an algorithm share its banners too.
|
||||
|
||||
// Classical key sizes, the composite keys of version 3 add the post-quantum key to these.
|
||||
const (
|
||||
x25519KeySize = 32
|
||||
p256PublicKeySize = 65 // uncompressed
|
||||
p256PrivateKeySize = 32
|
||||
ed25519PublicKeySize = 32
|
||||
ed25519PrivateKeySize = 64
|
||||
ecdsaP256PublicKeySize = 65 // uncompressed
|
||||
)
|
||||
|
||||
// ClassicalPrivateKey returns the classical half of a host private key: all of a classical key, or the classical half
|
||||
// of a composite one, whatever its suite.
|
||||
func ClassicalPrivateKey(key []byte) []byte {
|
||||
// X25519 and P256 private keys are the same size.
|
||||
if len(key) > x25519KeySize {
|
||||
return key[:x25519KeySize]
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
// pqKeyKind is what a composite key banner holds.
|
||||
type pqKeyKind int
|
||||
|
||||
const (
|
||||
pqPrivateKey pqKeyKind = iota
|
||||
pqPublicKey
|
||||
pqSigningPrivateKey
|
||||
pqSigningPublicKey
|
||||
pqEncryptedSigningPrivateKey
|
||||
)
|
||||
|
||||
// pqKeyBanner is what a composite key banner says about the key under it.
|
||||
type pqKeyBanner struct {
|
||||
kind pqKeyKind
|
||||
curve Curve
|
||||
size int // of the whole composite key; for an encrypted key, once decrypted
|
||||
}
|
||||
|
||||
var pqKeyKinds = []pqKeyKind{pqPrivateKey, pqPublicKey, pqSigningPrivateKey, pqSigningPublicKey, pqEncryptedSigningPrivateKey}
|
||||
|
||||
// pqKeyBanners maps every composite key banner of every suite to what it holds, see registerPQSuite.
|
||||
var pqKeyBanners = map[string]pqKeyBanner{}
|
||||
|
||||
// pqBannerName returns the banner for a composite key.
|
||||
func pqBannerName(kind pqKeyKind, curve Curve, suite *pqSuite) string {
|
||||
classical := map[Curve]string{Curve_CURVE25519: "X25519", Curve_P256: "P256"}[curve]
|
||||
alg := suite.kem.name
|
||||
if kind != pqPrivateKey && kind != pqPublicKey {
|
||||
classical = map[Curve]string{Curve_CURVE25519: "ED25519", Curve_P256: "ECDSA P256"}[curve]
|
||||
alg = suite.dsa.name
|
||||
}
|
||||
return "NEBULA " + classical + " " + alg + " " + map[pqKeyKind]string{
|
||||
pqPrivateKey: "PRIVATE KEY",
|
||||
pqPublicKey: "PUBLIC KEY",
|
||||
pqSigningPrivateKey: "PRIVATE KEY",
|
||||
pqSigningPublicKey: "PUBLIC KEY",
|
||||
pqEncryptedSigningPrivateKey: "ENCRYPTED PRIVATE KEY",
|
||||
}[kind]
|
||||
}
|
||||
|
||||
// pqKeySize returns the size of a composite key.
|
||||
func pqKeySize(kind pqKeyKind, curve Curve, suite *pqSuite) int {
|
||||
p256 := curve == Curve_P256
|
||||
switch kind {
|
||||
case pqPrivateKey:
|
||||
return x25519KeySize + suite.kem.privateKeySize // a P256 private key is the same size
|
||||
case pqPublicKey:
|
||||
return map[bool]int{false: x25519KeySize, true: p256PublicKeySize}[p256] + suite.kem.publicKeySize
|
||||
case pqSigningPublicKey:
|
||||
return map[bool]int{false: ed25519PublicKeySize, true: ecdsaP256PublicKeySize}[p256] + suite.dsa.publicKeySize
|
||||
default:
|
||||
return map[bool]int{false: ed25519PrivateKeySize, true: p256PrivateKeySize}[p256] + suite.dsa.privateKeySize
|
||||
}
|
||||
}
|
||||
|
||||
// marshalPQKeyToPEM PEM encodes a composite key of suite, nil for an unknown curve or suite or a key of the wrong size.
|
||||
func marshalPQKeyToPEM(kind pqKeyKind, curve Curve, suite PQSuite, b []byte) []byte {
|
||||
p := pqSuites[suite]
|
||||
if p == nil || (curve != Curve_CURVE25519 && curve != Curve_P256) || len(b) != pqKeySize(kind, curve, p) {
|
||||
return nil
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: pqBannerName(kind, curve, p), Bytes: b})
|
||||
}
|
||||
|
||||
// unmarshalPQKeyBlock checks a PEM block that may hold a composite key of one of kinds. ok is false when the banner
|
||||
// is not a composite key banner of those kinds at all.
|
||||
func unmarshalPQKeyBlock(k *pem.Block, kinds ...pqKeyKind) (curve Curve, ok bool, err error) {
|
||||
b, found := pqKeyBanners[k.Type]
|
||||
if !found || !slices.Contains(kinds, b.kind) {
|
||||
return 0, false, nil
|
||||
}
|
||||
if b.kind != pqEncryptedSigningPrivateKey && len(k.Bytes) != b.size {
|
||||
return b.curve, true, fmt.Errorf("key was not %d bytes, is invalid %s", b.size, strings.ToLower(strings.TrimPrefix(k.Type, "NEBULA ")))
|
||||
}
|
||||
return b.curve, true, nil
|
||||
}
|
||||
|
||||
/* including "ECDSA" in the P256 banners is a clue that these keys should be used only for signing */
|
||||
const ( //signing key banners
|
||||
EncryptedECDSAP256PrivateKeyBanner = "NEBULA ECDSA P256 ENCRYPTED PRIVATE KEY"
|
||||
@@ -109,12 +215,20 @@ func unmarshalCertificateBlock(block *pem.Block) (Certificate, error) {
|
||||
return unmarshalCertificateV1(block.Bytes, nil)
|
||||
case CertificateV2Banner:
|
||||
return unmarshalCertificateV2(block.Bytes, nil, Curve_CURVE25519)
|
||||
case CertificateV3Banner:
|
||||
return unmarshalCertificateV3(block.Bytes, nil, Curve_CURVE25519)
|
||||
default:
|
||||
return nil, ErrInvalidPEMCertificateBanner
|
||||
}
|
||||
}
|
||||
|
||||
func marshalCertPublicKeyToPEM(c Certificate) []byte {
|
||||
if suite := PQSuiteOf(c); suite != PQSuiteUnknown {
|
||||
if c.IsCA() {
|
||||
return MarshalPQSigningPublicKeyToPEM(c.Curve(), suite, c.PublicKey())
|
||||
}
|
||||
return MarshalPQPublicKeyToPEM(c.Curve(), suite, c.PublicKey())
|
||||
}
|
||||
if c.IsCA() {
|
||||
return MarshalSigningPublicKeyToPEM(c.Curve(), c.PublicKey())
|
||||
} else {
|
||||
@@ -135,6 +249,12 @@ func MarshalPublicKeyToPEM(curve Curve, b []byte) []byte {
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalPQPublicKeyToPEM returns a PEM representation of a composite host public key of suite, the classical ECDH
|
||||
// key followed by the suite's KEM public key, or nil if b is not one.
|
||||
func MarshalPQPublicKeyToPEM(curve Curve, suite PQSuite, b []byte) []byte {
|
||||
return marshalPQKeyToPEM(pqPublicKey, curve, suite, b)
|
||||
}
|
||||
|
||||
// MarshalSigningPublicKeyToPEM returns a PEM representation of a public key used for signing.
|
||||
// if your public key came from a certificate, prefer Certificate.PublicKeyPEM() if possible, to avoid mistakes!
|
||||
func MarshalSigningPublicKeyToPEM(curve Curve, b []byte) []byte {
|
||||
@@ -148,6 +268,12 @@ func MarshalSigningPublicKeyToPEM(curve Curve, b []byte) []byte {
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalPQSigningPublicKeyToPEM returns a PEM representation of a composite CA public key of suite, the classical
|
||||
// signing key followed by the public key of the suite's signature algorithm, or nil if b is not one.
|
||||
func MarshalPQSigningPublicKeyToPEM(curve Curve, suite PQSuite, b []byte) []byte {
|
||||
return marshalPQKeyToPEM(pqSigningPublicKey, curve, suite, b)
|
||||
}
|
||||
|
||||
// UnmarshalPublicKeyFromPEM will try to unmarshal the first pem block in a byte array, returning any non
|
||||
// consumed data or an error on failure. Only key-agreement (ECDH) public key banners are accepted.
|
||||
// Use UnmarshalSigningPublicKeyFromPEM for Ed25519/ECDSA banners.
|
||||
@@ -156,6 +282,12 @@ func UnmarshalPublicKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
|
||||
if k == nil {
|
||||
return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
|
||||
}
|
||||
if curve, ok, err := unmarshalPQKeyBlock(k, pqPublicKey); ok {
|
||||
if err != nil {
|
||||
return nil, r, 0, err
|
||||
}
|
||||
return k.Bytes, r, curve, nil
|
||||
}
|
||||
var expectedLen int
|
||||
var curve Curve
|
||||
switch k.Type {
|
||||
@@ -183,6 +315,12 @@ func UnmarshalSigningPublicKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
|
||||
if k == nil {
|
||||
return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
|
||||
}
|
||||
if curve, ok, err := unmarshalPQKeyBlock(k, pqSigningPublicKey); ok {
|
||||
if err != nil {
|
||||
return nil, r, 0, err
|
||||
}
|
||||
return k.Bytes, r, curve, nil
|
||||
}
|
||||
var expectedLen int
|
||||
var curve Curve
|
||||
switch k.Type {
|
||||
@@ -213,6 +351,18 @@ func MarshalPrivateKeyToPEM(curve Curve, b []byte) []byte {
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalPQPrivateKeyToPEM returns a PEM representation of a composite host private key of suite, the classical ECDH
|
||||
// key followed by the seed of the suite's KEM, or nil if b is not one.
|
||||
func MarshalPQPrivateKeyToPEM(curve Curve, suite PQSuite, b []byte) []byte {
|
||||
return marshalPQKeyToPEM(pqPrivateKey, curve, suite, b)
|
||||
}
|
||||
|
||||
// MarshalPQSigningPrivateKeyToPEM returns a PEM representation of a composite CA private key of suite, the classical
|
||||
// signing key followed by the seed of the suite's signature algorithm, or nil if b is not one.
|
||||
func MarshalPQSigningPrivateKeyToPEM(curve Curve, suite PQSuite, b []byte) []byte {
|
||||
return marshalPQKeyToPEM(pqSigningPrivateKey, curve, suite, b)
|
||||
}
|
||||
|
||||
func MarshalSigningPrivateKeyToPEM(curve Curve, b []byte) []byte {
|
||||
switch curve {
|
||||
case Curve_CURVE25519:
|
||||
@@ -231,6 +381,12 @@ func UnmarshalPrivateKeyFromPEM(b []byte) ([]byte, []byte, Curve, error) {
|
||||
if k == nil {
|
||||
return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
|
||||
}
|
||||
if curve, ok, err := unmarshalPQKeyBlock(k, pqPrivateKey); ok {
|
||||
if err != nil {
|
||||
return nil, r, 0, err
|
||||
}
|
||||
return k.Bytes, r, curve, nil
|
||||
}
|
||||
var expectedLen int
|
||||
var curve Curve
|
||||
switch k.Type {
|
||||
@@ -254,6 +410,15 @@ func UnmarshalSigningPrivateKeyFromPEM(b []byte) ([]byte, []byte, Curve, error)
|
||||
if k == nil {
|
||||
return nil, r, 0, fmt.Errorf("input did not contain a valid PEM encoded block")
|
||||
}
|
||||
if curve, ok, err := unmarshalPQKeyBlock(k, pqSigningPrivateKey, pqEncryptedSigningPrivateKey); ok {
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, r, 0, err
|
||||
case pqKeyBanners[k.Type].kind == pqEncryptedSigningPrivateKey:
|
||||
return nil, nil, curve, ErrPrivateKeyEncrypted
|
||||
}
|
||||
return k.Bytes, r, curve, nil
|
||||
}
|
||||
var curve Curve
|
||||
switch k.Type {
|
||||
case EncryptedEd25519PrivateKeyBanner:
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"crypto/mldsa"
|
||||
"crypto/mlkem"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PQSuite names the post-quantum algorithms of a version 3 certificate, the way Curve names its classical ones: the
|
||||
// key encapsulation mechanism of a host's key, and the signature algorithm of a CA's key and of the certificates it
|
||||
// signs. A CA and every certificate it signs share a suite. Every version 3 certificate names its suite.
|
||||
type PQSuite uint8
|
||||
|
||||
const (
|
||||
// PQSuiteUnknown is never valid in a certificate.
|
||||
PQSuiteUnknown PQSuite = 0
|
||||
|
||||
// PQSuite_MLKEM1024_MLDSA87 gives hosts ML-KEM-1024 keys and CAs ML-DSA-87 keys and signatures.
|
||||
PQSuite_MLKEM1024_MLDSA87 PQSuite = 1
|
||||
)
|
||||
|
||||
// DefaultPQSuite is the suite tools use when none is asked for.
|
||||
const DefaultPQSuite = PQSuite_MLKEM1024_MLDSA87
|
||||
|
||||
// pqKEM is the key encapsulation mechanism of a suite, what host keys use. Private keys are seeds.
|
||||
type pqKEM struct {
|
||||
name string // as it appears in key banners
|
||||
publicKeySize int
|
||||
privateKeySize int
|
||||
generate func() (pub, priv []byte, err error)
|
||||
publicKey func(priv []byte) ([]byte, error)
|
||||
checkPublicKey func(pub []byte) bool
|
||||
}
|
||||
|
||||
// pqDSA is the signature algorithm of a suite, what CA keys and certificate signatures use. Private keys are seeds.
|
||||
type pqDSA struct {
|
||||
name string // as it appears in key banners
|
||||
publicKeySize int
|
||||
privateKeySize int
|
||||
signatureSize int
|
||||
generate func() (pub, priv []byte, err error)
|
||||
publicKey func(priv []byte) ([]byte, error)
|
||||
checkPublicKey func(pub []byte) bool
|
||||
signer func(priv []byte) (SignerLambda, error) // must sign deterministically
|
||||
verify func(pub, msg, sig []byte) bool
|
||||
}
|
||||
|
||||
type pqSuite struct {
|
||||
kem pqKEM
|
||||
dsa pqDSA
|
||||
}
|
||||
|
||||
// pqSuites holds every known suite, see registerPQSuite.
|
||||
var pqSuites = map[PQSuite]*pqSuite{}
|
||||
|
||||
func init() {
|
||||
registerPQSuite(PQSuite_MLKEM1024_MLDSA87, &pqSuite{kem: mlkem1024, dsa: mldsa87})
|
||||
}
|
||||
|
||||
// registerPQSuite makes a suite known, along with the banners of its composite keys.
|
||||
func registerPQSuite(id PQSuite, s *pqSuite) {
|
||||
pqSuites[id] = s
|
||||
for _, curve := range []Curve{Curve_CURVE25519, Curve_P256} {
|
||||
for _, kind := range pqKeyKinds {
|
||||
pqKeyBanners[pqBannerName(kind, curve, s)] = pqKeyBanner{kind: kind, curve: curve, size: pqKeySize(kind, curve, s)}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var mlkem1024 = pqKEM{
|
||||
name: "MLKEM1024",
|
||||
publicKeySize: mlkem.EncapsulationKeySize1024,
|
||||
privateKeySize: mlkem.SeedSize,
|
||||
generate: func() ([]byte, []byte, error) {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return dk.EncapsulationKey().Bytes(), dk.Bytes(), nil
|
||||
},
|
||||
publicKey: func(priv []byte) ([]byte, error) {
|
||||
dk, err := mlkem.NewDecapsulationKey1024(priv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dk.EncapsulationKey().Bytes(), nil
|
||||
},
|
||||
checkPublicKey: func(pub []byte) bool {
|
||||
return len(pub) == mlkem.EncapsulationKeySize1024 && mlkemModulusOK(pub[:len(pub)-32])
|
||||
},
|
||||
}
|
||||
|
||||
// mlkemModulusOK is the modulus check of FIPS 203 section 7.2, the one crypto/mlkem runs on an encapsulation key: t,
|
||||
// the key less its trailing 32 byte seed, packs 12 bit coefficients that must all be below q. crypto/mlkem would also
|
||||
// expand the seed into the ~10KB matrix of an encapsulation key, which a certificate check has no use for.
|
||||
func mlkemModulusOK(t []byte) bool {
|
||||
const q = 3329
|
||||
for i := 0; i+3 <= len(t); i += 3 {
|
||||
d1 := uint16(t[i]) | uint16(t[i+1]&0x0f)<<8
|
||||
d2 := uint16(t[i+1]>>4) | uint16(t[i+2])<<4
|
||||
if d1 >= q || d2 >= q {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var mldsa87 = pqDSA{
|
||||
name: "MLDSA87",
|
||||
publicKeySize: mldsa.MLDSA87PublicKeySize,
|
||||
privateKeySize: mldsa.PrivateKeySize,
|
||||
signatureSize: mldsa.MLDSA87SignatureSize,
|
||||
generate: func() ([]byte, []byte, error) {
|
||||
sk, err := mldsa.GenerateKey(mldsa.MLDSA87())
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return sk.PublicKey().Bytes(), sk.Bytes(), nil
|
||||
},
|
||||
publicKey: func(priv []byte) ([]byte, error) {
|
||||
sk, err := mldsa.NewPrivateKey(mldsa.MLDSA87(), priv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sk.PublicKey().Bytes(), nil
|
||||
},
|
||||
checkPublicKey: func(pub []byte) bool {
|
||||
_, err := mldsa.NewPublicKey(mldsa.MLDSA87(), pub)
|
||||
return err == nil
|
||||
},
|
||||
// Deterministic signing (FIPS 204 section 3.4): the hedged variant guards signers an attacker can fault
|
||||
// physically, which a CA key in a file is not, and the Ed25519 signature beside it is deterministic too.
|
||||
signer: func(priv []byte) (SignerLambda, error) {
|
||||
sk, err := mldsa.NewPrivateKey(mldsa.MLDSA87(), priv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return func(b []byte) ([]byte, error) {
|
||||
return sk.SignDeterministic(b, &mldsa.Options{Context: pqSignatureContext})
|
||||
}, nil
|
||||
},
|
||||
verify: func(pub, msg, sig []byte) bool {
|
||||
pk, err := mldsa.NewPublicKey(mldsa.MLDSA87(), pub)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return mldsa.Verify(pk, msg, sig, &mldsa.Options{Context: pqSignatureContext}) == nil
|
||||
},
|
||||
}
|
||||
|
||||
// PQSuites returns every known suite.
|
||||
func PQSuites() []PQSuite {
|
||||
s := make([]PQSuite, 0, len(pqSuites))
|
||||
for k := range pqSuites {
|
||||
s = append(s, k)
|
||||
}
|
||||
slices.Sort(s)
|
||||
return s
|
||||
}
|
||||
|
||||
// ParsePQSuite returns the suite named by s, as String names it, ignoring case.
|
||||
func ParsePQSuite(s string) (PQSuite, error) {
|
||||
for _, k := range PQSuites() {
|
||||
if strings.EqualFold(s, k.String()) {
|
||||
return k, nil
|
||||
}
|
||||
}
|
||||
return PQSuiteUnknown, fmt.Errorf("%w: %q", ErrUnknownPQSuite, s)
|
||||
}
|
||||
|
||||
// PQSuiteOf returns the suite of a version 3 certificate, or PQSuiteUnknown for any other version.
|
||||
func PQSuiteOf(c Certificate) PQSuite {
|
||||
if c3, ok := c.(*certificateV3); ok {
|
||||
return c3.pqSuite
|
||||
}
|
||||
return PQSuiteUnknown
|
||||
}
|
||||
|
||||
func (s PQSuite) String() string {
|
||||
if p := pqSuites[s]; p != nil {
|
||||
return p.kem.name + "_" + p.dsa.name
|
||||
}
|
||||
return fmt.Sprintf("PQSuite(%d)", uint8(s))
|
||||
}
|
||||
|
||||
// Valid reports whether s is a known suite.
|
||||
func (s PQSuite) Valid() bool {
|
||||
return pqSuites[s] != nil
|
||||
}
|
||||
|
||||
// PublicKeySize returns the size of the post-quantum half of a composite public key, a CA's or a host's.
|
||||
func (s PQSuite) PublicKeySize(isCA bool) int {
|
||||
p := pqSuites[s]
|
||||
switch {
|
||||
case p == nil:
|
||||
return 0
|
||||
case isCA:
|
||||
return p.dsa.publicKeySize
|
||||
default:
|
||||
return p.kem.publicKeySize
|
||||
}
|
||||
}
|
||||
|
||||
// PrivateKeySize returns the size of the post-quantum half of a composite private key, a CA's or a host's.
|
||||
func (s PQSuite) PrivateKeySize(isCA bool) int {
|
||||
p := pqSuites[s]
|
||||
switch {
|
||||
case p == nil:
|
||||
return 0
|
||||
case isCA:
|
||||
return p.dsa.privateKeySize
|
||||
default:
|
||||
return p.kem.privateKeySize
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateKey makes a post-quantum keypair, a CA's signing key or a host's KEM key, to append to a classical one.
|
||||
func (s PQSuite) GenerateKey(isCA bool) (pub, priv []byte, err error) {
|
||||
p := pqSuites[s]
|
||||
switch {
|
||||
case p == nil:
|
||||
return nil, nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, s)
|
||||
case isCA:
|
||||
return p.dsa.generate()
|
||||
default:
|
||||
return p.kem.generate()
|
||||
}
|
||||
}
|
||||
|
||||
// publicKey derives the post-quantum public key from the post-quantum half of a private key.
|
||||
func (s PQSuite) publicKey(isCA bool, priv []byte) ([]byte, error) {
|
||||
p := pqSuites[s]
|
||||
switch {
|
||||
case p == nil:
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, s)
|
||||
case isCA:
|
||||
return p.dsa.publicKey(priv)
|
||||
default:
|
||||
return p.kem.publicKey(priv)
|
||||
}
|
||||
}
|
||||
|
||||
// checkPublicKey reports whether pub is a well formed post-quantum public key, a CA's or a host's.
|
||||
func (s PQSuite) checkPublicKey(isCA bool, pub []byte) bool {
|
||||
p := pqSuites[s]
|
||||
switch {
|
||||
case p == nil, len(pub) != s.PublicKeySize(isCA):
|
||||
return false
|
||||
case isCA:
|
||||
return p.dsa.checkPublicKey(pub)
|
||||
default:
|
||||
return p.kem.checkPublicKey(pub)
|
||||
}
|
||||
}
|
||||
|
||||
// signatureSize returns the size of the post-quantum signature of a certificate in this suite.
|
||||
func (s PQSuite) signatureSize() int {
|
||||
if p := pqSuites[s]; p != nil {
|
||||
return p.dsa.signatureSize
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// SplitPublicKey splits a composite public key into its classical and post-quantum halves.
|
||||
func (s PQSuite) SplitPublicKey(isCA bool, key []byte) (classical, pq []byte, err error) {
|
||||
n := s.PublicKeySize(isCA)
|
||||
if n == 0 || len(key) <= n {
|
||||
return nil, nil, ErrInvalidPublicKey
|
||||
}
|
||||
return key[:len(key)-n], key[len(key)-n:], nil
|
||||
}
|
||||
|
||||
// SplitPrivateKey splits a composite private key into its classical and post-quantum halves.
|
||||
func (s PQSuite) SplitPrivateKey(isCA bool, key []byte) (classical, pq []byte, err error) {
|
||||
n := s.PrivateKeySize(isCA)
|
||||
if n == 0 || len(key) <= n {
|
||||
return nil, nil, ErrInvalidPrivateKey
|
||||
}
|
||||
return key[:len(key)-n], key[len(key)-n:], nil
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package cert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mlkem"
|
||||
"crypto/rand"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testPQSuite stands in for a second suite. It reuses ML-KEM-1024 and ML-DSA-87 under other names, so it is
|
||||
// interchangeable with the default suite in everything but its identity, which is what has to keep them apart.
|
||||
const testPQSuite PQSuite = 200
|
||||
|
||||
func registerTestPQSuite(t *testing.T) {
|
||||
t.Helper()
|
||||
kem, dsa := mlkem1024, mldsa87
|
||||
kem.name, dsa.name = "TESTKEM", "TESTDSA"
|
||||
registerPQSuite(testPQSuite, &pqSuite{kem: kem, dsa: dsa})
|
||||
t.Cleanup(func() {
|
||||
delete(pqSuites, testPQSuite)
|
||||
for k := range pqKeyBanners {
|
||||
if strings.Contains(k, "TESTKEM") || strings.Contains(k, "TESTDSA") {
|
||||
delete(pqKeyBanners, k)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// newTestV3InSuite issues a v3 CA and host certificate in suite.
|
||||
func newTestV3InSuite(t *testing.T, curve Curve, suite PQSuite) (ca Certificate, caKey []byte, host Certificate, hostKey []byte) {
|
||||
t.Helper()
|
||||
ca2, _, caKey2, _ := NewTestCaCert(Version2, curve, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
pqPub, pqPriv, err := suite.GenerateKey(true)
|
||||
require.NoError(t, err)
|
||||
signPQ, err := SignPQ(suite, pqPriv)
|
||||
require.NoError(t, err)
|
||||
ca, err = ExtendToV3(ca2, suite, pqPub, nil, signPQ)
|
||||
require.NoError(t, err)
|
||||
caKey = append(caKey2, pqPriv...)
|
||||
|
||||
var pub, priv []byte
|
||||
if curve == Curve_P256 {
|
||||
pub, priv = P256Keypair()
|
||||
} else {
|
||||
pub, priv = X25519Keypair()
|
||||
}
|
||||
hostPQPub, hostPQPriv, err := suite.GenerateKey(false)
|
||||
require.NoError(t, err)
|
||||
tbs := &TBSCertificate{
|
||||
Version: Version3,
|
||||
Curve: curve,
|
||||
PQSuite: suite,
|
||||
Name: "host",
|
||||
Networks: []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")},
|
||||
NotBefore: ca.NotBefore(),
|
||||
NotAfter: ca.NotAfter(),
|
||||
PublicKey: append(pub, hostPQPub...),
|
||||
}
|
||||
host, err = tbs.Sign(ca, curve, caKey)
|
||||
require.NoError(t, err)
|
||||
return ca, caKey, host, append(priv, hostPQPriv...)
|
||||
}
|
||||
|
||||
func TestPQSuite_Names(t *testing.T) {
|
||||
assert.Equal(t, "MLKEM1024_MLDSA87", PQSuite_MLKEM1024_MLDSA87.String())
|
||||
assert.Equal(t, []PQSuite{PQSuite_MLKEM1024_MLDSA87}, PQSuites())
|
||||
assert.False(t, PQSuiteUnknown.Valid())
|
||||
|
||||
s, err := ParsePQSuite("mlkem1024_mldsa87")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, PQSuite_MLKEM1024_MLDSA87, s)
|
||||
_, err = ParsePQSuite("mlkem768_mldsa65")
|
||||
require.ErrorIs(t, err, ErrUnknownPQSuite)
|
||||
|
||||
_, _, host, _ := newTestV3(t, Curve_CURVE25519)
|
||||
assert.Equal(t, DefaultPQSuite, PQSuiteOf(host))
|
||||
assert.Equal(t, PQSuiteUnknown, PQSuiteOf(V2Form(host)))
|
||||
}
|
||||
|
||||
// A second suite works end to end, and is never confused with the first, even with keys of the same sizes.
|
||||
func TestPQSuite_Second(t *testing.T) {
|
||||
registerTestPQSuite(t)
|
||||
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, caKey, host, hostKey := newTestV3InSuite(t, curve, testPQSuite)
|
||||
assert.Equal(t, testPQSuite, PQSuiteOf(ca))
|
||||
assert.Equal(t, testPQSuite, PQSuiteOf(host))
|
||||
require.NoError(t, ca.VerifyPrivateKey(curve, caKey))
|
||||
require.NoError(t, host.VerifyPrivateKey(curve, hostKey))
|
||||
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
_, err := pool.VerifyCertificate(time.Now(), host)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The suite travels in the certificate, handshakes included.
|
||||
hs, err := host.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
c, err := Recombine(Version3, hs, host.PublicKey(), curve)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testPQSuite, PQSuiteOf(c))
|
||||
assertCertsEqual(t, host, c)
|
||||
|
||||
// Keys get their algorithms' banners.
|
||||
b := MarshalPQPrivateKeyToPEM(curve, testPQSuite, hostKey)
|
||||
assert.Contains(t, string(b), " TESTKEM PRIVATE KEY-----")
|
||||
key, _, _, err := UnmarshalPrivateKeyFromPEM(b)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, hostKey, key)
|
||||
assert.Contains(t, string(host.MarshalPublicKeyPEM()), " TESTKEM PUBLIC KEY-----")
|
||||
assert.Contains(t, string(ca.MarshalPublicKeyPEM()), " TESTDSA PUBLIC KEY-----")
|
||||
|
||||
// The suite is signed: relabelling a certificate breaks it, though the keys fit either suite.
|
||||
_, _, other, _ := newTestV3(t, curve)
|
||||
relabelled := other.Copy().(*certificateV3)
|
||||
relabelled.pqSuite = testPQSuite
|
||||
assert.False(t, relabelled.CheckSignature(ca.PublicKey()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A CA and the certificates it signs share a suite, like they share a curve.
|
||||
func TestPQSuite_Mismatch(t *testing.T) {
|
||||
registerTestPQSuite(t)
|
||||
|
||||
for _, curve := range testCurves {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
ca, caKey, host, _ := newTestV3(t, curve)
|
||||
|
||||
// Signing refuses a certificate in another suite than its CA.
|
||||
tbs := &TBSCertificate{
|
||||
Version: Version3, Curve: curve, PQSuite: testPQSuite, Name: "x",
|
||||
Networks: host.Networks(), NotBefore: host.NotBefore(), NotAfter: host.NotAfter(), PublicKey: host.PublicKey(),
|
||||
}
|
||||
_, err := tbs.Sign(ca, curve, caKey)
|
||||
require.ErrorIs(t, err, ErrPQSuiteMismatch)
|
||||
|
||||
// Extending refuses it too.
|
||||
v2CA := V2Form(ca)
|
||||
v2Host := V2Form(host)
|
||||
_, pqHost, err := DefaultPQSuite.SplitPublicKey(false, host.PublicKey())
|
||||
require.NoError(t, err)
|
||||
signPQ, err := SignPQ(DefaultPQSuite, caKey[len(caKey)-DefaultPQSuite.PrivateKeySize(true):])
|
||||
require.NoError(t, err)
|
||||
_, err = ExtendToV3(v2Host, testPQSuite, pqHost, ca, signPQ)
|
||||
require.ErrorIs(t, err, ErrPQSuiteMismatch)
|
||||
|
||||
// The pool rejects a certificate whose CA, found by issuer, is in another suite: here the same v2 CA
|
||||
// extended once per suite, with only the default suite's extension trusted.
|
||||
pqPub, pqPriv, err := testPQSuite.GenerateKey(true)
|
||||
require.NoError(t, err)
|
||||
signOther, err := SignPQ(testPQSuite, pqPriv)
|
||||
require.NoError(t, err)
|
||||
otherCA, err := ExtendToV3(v2CA, testPQSuite, pqPub, nil, signOther)
|
||||
require.NoError(t, err)
|
||||
otherHost, err := ExtendToV3(v2Host, testPQSuite, pqHost, otherCA, signOther)
|
||||
require.NoError(t, err)
|
||||
|
||||
pool := NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
_, err = pool.VerifyCertificate(time.Now(), otherHost)
|
||||
require.ErrorIs(t, err, ErrPQSuiteMismatch)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMLKEMModulusOK(t *testing.T) {
|
||||
stdlib := func(pub []byte) bool {
|
||||
_, err := mlkem.NewEncapsulationKey1024(pub)
|
||||
return err == nil
|
||||
}
|
||||
setCoeff := func(pub []byte, i int, v uint16) {
|
||||
b := pub[i/2*3:]
|
||||
if i%2 == 0 {
|
||||
b[0] = byte(v)
|
||||
b[1] = b[1]&0xf0 | byte(v>>8)
|
||||
} else {
|
||||
b[1] = b[1]&0x0f | byte(v<<4)
|
||||
b[2] = byte(v >> 4)
|
||||
}
|
||||
}
|
||||
|
||||
for range 8 {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
pub := dk.EncapsulationKey().Bytes()
|
||||
require.True(t, mlkem1024.checkPublicKey(pub))
|
||||
for _, i := range []int{0, 1, 2, 3, 511, 512, 1022, 1023} {
|
||||
for _, v := range []uint16{0, 3328, 3329, 4095} {
|
||||
p := bytes.Clone(pub)
|
||||
setCoeff(p, i, v)
|
||||
assert.Equal(t, stdlib(p), mlkem1024.checkPublicKey(p), "coefficient %d = %d", i, v)
|
||||
assert.Equal(t, v < 3329, mlkem1024.checkPublicKey(p), "coefficient %d = %d", i, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub := make([]byte, mlkem.EncapsulationKeySize1024)
|
||||
for range 64 {
|
||||
_, _ = rand.Read(pub)
|
||||
assert.Equal(t, stdlib(pub), mlkem1024.checkPublicKey(pub))
|
||||
}
|
||||
assert.False(t, mlkem1024.checkPublicKey(pub[:len(pub)-1]))
|
||||
}
|
||||
+75
-8
@@ -26,6 +26,7 @@ type TBSCertificate struct {
|
||||
NotAfter time.Time
|
||||
PublicKey []byte
|
||||
Curve Curve
|
||||
PQSuite PQSuite // version 3 only, the suite of the certificate and of its signing CA
|
||||
issuer string
|
||||
}
|
||||
|
||||
@@ -47,31 +48,95 @@ type SignerLambda func(certBytes []byte) ([]byte, error)
|
||||
// details do not violate constraints of the signing certificate.
|
||||
// If the TBSCertificate is a CA then signer must be nil.
|
||||
func (t *TBSCertificate) Sign(signer Certificate, curve Curve, key []byte) (Certificate, error) {
|
||||
switch t.Curve {
|
||||
if t.Version == Version3 {
|
||||
// The signing key is a composite CA key, classical || the seed of the suite's signature algorithm.
|
||||
classicalKey, pqKey, err := t.PQSuite.SplitPrivateKey(true, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
classical, err := classicalSigner(t.Curve, classicalKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pq, err := SignPQ(t.PQSuite, pqKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.SignHybridWith(signer, curve, classical, pq)
|
||||
}
|
||||
|
||||
sp, err := classicalSigner(t.Curve, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.SignWith(signer, curve, sp)
|
||||
}
|
||||
|
||||
// classicalSigner returns a SignerLambda for a classical signing private key.
|
||||
func classicalSigner(curve Curve, key []byte) (SignerLambda, error) {
|
||||
switch curve {
|
||||
case Curve_CURVE25519:
|
||||
if len(key) != ed25519.PrivateKeySize {
|
||||
return nil, ErrInvalidPrivateKey
|
||||
}
|
||||
pk := ed25519.PrivateKey(key)
|
||||
sp := func(certBytes []byte) ([]byte, error) {
|
||||
return func(certBytes []byte) ([]byte, error) {
|
||||
sig := ed25519.Sign(pk, certBytes)
|
||||
return sig, nil
|
||||
}
|
||||
return t.SignWith(signer, curve, sp)
|
||||
}, nil
|
||||
case Curve_P256:
|
||||
pk, err := ecdsa.ParseRawPrivateKey(elliptic.P256(), key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sp := func(certBytes []byte) ([]byte, error) {
|
||||
return func(certBytes []byte) ([]byte, error) {
|
||||
// We need to hash first for ECDSA
|
||||
// - https://pkg.go.dev/crypto/ecdsa#SignASN1
|
||||
hashed := sha256.Sum256(certBytes)
|
||||
return ecdsa.SignASN1(rand.Reader, pk, hashed[:])
|
||||
}
|
||||
return t.SignWith(signer, curve, sp)
|
||||
}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid curve: %s", t.Curve)
|
||||
return nil, fmt.Errorf("invalid curve: %s", curve)
|
||||
}
|
||||
}
|
||||
|
||||
// SignHybridWith signs a version 3 certificate, using sp for the classical signature and pqSp for the post-quantum
|
||||
// signature of t.PQSuite. t.PublicKey is the composite public key. signer must be a version 3 CA in the same suite,
|
||||
// or nil for a self signed CA. The v2 form is signed exactly as SignWith would sign it, and so is the v2 form of
|
||||
// signer.
|
||||
func (t *TBSCertificate) SignHybridWith(signer Certificate, curve Curve, sp, pqSp SignerLambda) (Certificate, error) {
|
||||
if t.Version != Version3 {
|
||||
return nil, fmt.Errorf("SignHybridWith only signs version 3 certificates")
|
||||
}
|
||||
if !t.PQSuite.Valid() {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnknownPQSuite, t.PQSuite)
|
||||
}
|
||||
classical, pq, err := t.PQSuite.SplitPublicKey(t.IsCA, t.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var signerV2 Certificate
|
||||
if signer != nil {
|
||||
if signer.Version() != Version3 {
|
||||
return nil, fmt.Errorf("a version 3 certificate must be signed by a version 3 CA")
|
||||
}
|
||||
if PQSuiteOf(signer) != t.PQSuite {
|
||||
return nil, ErrPQSuiteMismatch
|
||||
}
|
||||
signerV2 = V2Form(signer)
|
||||
}
|
||||
|
||||
t2 := *t
|
||||
t2.Version = Version2
|
||||
t2.PublicKey = classical
|
||||
c2, err := t2.SignWith(signerV2, curve, sp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ExtendToV3(c2, t.PQSuite, pq, signer, pqSp)
|
||||
}
|
||||
|
||||
// SignWith does the same thing as sign, but uses the function in `sp` to calculate the signature.
|
||||
// You should only use SignWith if you do not have direct access to your private key.
|
||||
func (t *TBSCertificate) SignWith(signer Certificate, curve Curve, sp SignerLambda) (Certificate, error) {
|
||||
@@ -114,6 +179,8 @@ func (t *TBSCertificate) SignWith(signer Certificate, curve Curve, sp SignerLamb
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case Version3:
|
||||
return nil, fmt.Errorf("version 3 certificates carry two signatures, use SignHybridWith")
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown cert version %d", t.Version)
|
||||
}
|
||||
|
||||
@@ -40,6 +40,10 @@ func NewTestCaCert(version cert.Version, curve cert.Curve, before, after time.Ti
|
||||
// There is no default to allow the underlying lib to respond with an error
|
||||
}
|
||||
|
||||
if version == cert.Version3 {
|
||||
pub, priv = appendPQSigningKey(pub, priv)
|
||||
}
|
||||
|
||||
if before.IsZero() {
|
||||
before = testCertNow.Add(time.Second * -60)
|
||||
}
|
||||
@@ -59,6 +63,9 @@ func NewTestCaCert(version cert.Version, curve cert.Curve, before, after time.Ti
|
||||
Groups: groups,
|
||||
IsCA: true,
|
||||
}
|
||||
if version == cert.Version3 {
|
||||
t.PQSuite = cert.DefaultPQSuite
|
||||
}
|
||||
|
||||
c, err := t.Sign(nil, curve, priv)
|
||||
if err != nil {
|
||||
@@ -94,6 +101,10 @@ func NewTestCert(v cert.Version, curve cert.Curve, ca cert.Certificate, key []by
|
||||
panic("unknown curve")
|
||||
}
|
||||
|
||||
if v == cert.Version3 {
|
||||
pub, priv = appendPQKey(ca, pub, priv)
|
||||
}
|
||||
|
||||
nc := &cert.TBSCertificate{
|
||||
Version: v,
|
||||
Curve: curve,
|
||||
@@ -105,6 +116,7 @@ func NewTestCert(v cert.Version, curve cert.Curve, ca cert.Certificate, key []by
|
||||
NotAfter: time.Unix(after.Unix(), 0),
|
||||
PublicKey: pub,
|
||||
IsCA: false,
|
||||
PQSuite: cert.PQSuiteOf(ca),
|
||||
}
|
||||
|
||||
c, err := nc.Sign(ca, ca.Curve(), key)
|
||||
@@ -117,6 +129,9 @@ func NewTestCert(v cert.Version, curve cert.Curve, ca cert.Certificate, key []by
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if v == cert.Version3 {
|
||||
return c, pub, cert.MarshalPQPrivateKeyToPEM(curve, cert.PQSuiteOf(ca), priv), pem
|
||||
}
|
||||
return c, pub, cert.MarshalPrivateKeyToPEM(curve, priv), pem
|
||||
}
|
||||
|
||||
@@ -132,6 +147,7 @@ func NewTestCertDifferentVersion(c cert.Certificate, v cert.Version, ca cert.Cer
|
||||
NotAfter: time.Unix(c.NotAfter().Unix(), 0),
|
||||
PublicKey: c.PublicKey(),
|
||||
IsCA: false,
|
||||
PQSuite: cert.PQSuiteOf(ca),
|
||||
}
|
||||
|
||||
c, err := nc.Sign(ca, ca.Curve(), key)
|
||||
@@ -147,6 +163,24 @@ func NewTestCertDifferentVersion(c cert.Certificate, v cert.Version, ca cert.Cer
|
||||
return c, pem
|
||||
}
|
||||
|
||||
// appendPQSigningKey makes a classical CA keypair into a version 3 composite one with a fresh key of the default suite.
|
||||
func appendPQSigningKey(pub, priv []byte) ([]byte, []byte) {
|
||||
pqPub, pqPriv, err := cert.DefaultPQSuite.GenerateKey(true)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...)
|
||||
}
|
||||
|
||||
// appendPQKey makes a classical host keypair into a version 3 composite one with a fresh key of the CA's suite.
|
||||
func appendPQKey(ca cert.Certificate, pub, priv []byte) ([]byte, []byte) {
|
||||
pqPub, pqPriv, err := cert.PQSuiteOf(ca).GenerateKey(false)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...)
|
||||
}
|
||||
|
||||
func X25519Keypair() ([]byte, []byte) {
|
||||
privkey := make([]byte, 32)
|
||||
if _, err := io.ReadFull(rand.Reader, privkey); err != nil {
|
||||
|
||||
+32
-8
@@ -37,6 +37,7 @@ type caFlags struct {
|
||||
argonParallelism *uint
|
||||
encryption *bool
|
||||
version *uint
|
||||
pqSuite *string
|
||||
|
||||
curve *string
|
||||
p11url *string
|
||||
@@ -71,7 +72,8 @@ func newCaFlags() *caFlags {
|
||||
cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
|
||||
cf.set.Usage = func() {}
|
||||
cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
|
||||
cf.version = cf.set.Uint("version", uint(cert.Version2), "Optional: version of the certificate format to use")
|
||||
cf.version = cf.set.Uint("version", uint(cert.Version2), "Optional: version of the certificate format to use. Version 3 adds a post-quantum key, for post-quantum certificates")
|
||||
cf.pqSuite = pqSuiteFlag(cf.set, "Optional: post-quantum suite of a version 3 CA, which the certificates it signs share")
|
||||
cf.duration = cf.set.Duration("duration", time.Duration(time.Hour*8760), "Optional: amount of time the certificate should be valid for. Valid time units are seconds: \"s\", minutes: \"m\", hours: \"h\"")
|
||||
cf.outKeyPath = cf.set.String("out-key", "ca.key", "Optional: path to write the private key to")
|
||||
cf.outCertPath = cf.set.String("out-crt", "ca.crt", "Optional: path to write the certificate to")
|
||||
@@ -160,8 +162,15 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
||||
}
|
||||
|
||||
version := cert.Version(*cf.version)
|
||||
if version != cert.Version1 && version != cert.Version2 {
|
||||
return newHelpErrorf("-version must be either %v or %v", cert.Version1, cert.Version2)
|
||||
if version != cert.Version1 && version != cert.Version2 && version != cert.Version3 {
|
||||
return newHelpErrorf("-version must be %v, %v or %v", cert.Version1, cert.Version2, cert.Version3)
|
||||
}
|
||||
if version == cert.Version3 && isP11 {
|
||||
return newHelpErrorf("-version 3 can not be used with -pkcs11, the post-quantum key has to be in out-key")
|
||||
}
|
||||
suite, err := parsePQSuiteFlag(cf.set, *cf.pqSuite, version == cert.Version3, "is only for -version 3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var networks []netip.Prefix
|
||||
@@ -295,6 +304,13 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
||||
default:
|
||||
return fmt.Errorf("invalid curve: %s", *cf.curve)
|
||||
}
|
||||
|
||||
if version == cert.Version3 {
|
||||
pub, rawPriv, err = appendPQSigningKey(suite, pub, rawPriv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t := &cert.TBSCertificate{
|
||||
@@ -309,6 +325,9 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
||||
IsCA: true,
|
||||
Curve: curve,
|
||||
}
|
||||
if version == cert.Version3 {
|
||||
t.PQSuite = suite
|
||||
}
|
||||
|
||||
if !isP11 && !isStdio(*cf.outKeyPath) {
|
||||
if _, err := os.Stat(*cf.outKeyPath); err == nil {
|
||||
@@ -336,14 +355,19 @@ func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error
|
||||
return fmt.Errorf("error while signing: %s", err)
|
||||
}
|
||||
|
||||
if *cf.encryption {
|
||||
switch {
|
||||
case *cf.encryption && version == cert.Version3:
|
||||
b, err = cert.EncryptAndMarshalPQSigningPrivateKey(curve, suite, rawPriv, passphrase, kdfParams)
|
||||
case *cf.encryption:
|
||||
b, err = cert.EncryptAndMarshalSigningPrivateKey(curve, rawPriv, passphrase, kdfParams)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while encrypting out-key: %s", err)
|
||||
}
|
||||
} else {
|
||||
case version == cert.Version3:
|
||||
b = cert.MarshalPQSigningPrivateKeyToPEM(curve, suite, rawPriv)
|
||||
default:
|
||||
b = cert.MarshalSigningPrivateKeyToPEM(curve, rawPriv)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while encrypting out-key: %s", err)
|
||||
}
|
||||
|
||||
err = writeOutput(*cf.outKeyPath, b, 0600, out)
|
||||
if err != nil {
|
||||
|
||||
@@ -68,12 +68,14 @@ func Test_caHelp(t *testing.T) {
|
||||
" -out-qr string\n"+
|
||||
" \tOptional: output a qr code image (png) of the certificate\n"+
|
||||
optionalPkcs11String(" -pkcs11 string\n \tOptional: PKCS#11 URI to an existing private key\n")+
|
||||
" -pq-suite string\n"+
|
||||
" \tOptional: post-quantum suite of a version 3 CA, which the certificates it signs share (MLKEM1024_MLDSA87) (default \"MLKEM1024_MLDSA87\")\n"+
|
||||
" -subnets string\n"+
|
||||
" \tDeprecated, see -unsafe-networks\n"+
|
||||
" -unsafe-networks string\n"+
|
||||
" \tOptional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in unsafe networks\n"+
|
||||
" -version uint\n"+
|
||||
" \tOptional: version of the certificate format to use (default 2)\n",
|
||||
" \tOptional: version of the certificate format to use. Version 3 adds a post-quantum key, for post-quantum certificates (default 2)\n",
|
||||
ob.String(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,10 @@ type keygenFlags struct {
|
||||
set *flag.FlagSet
|
||||
outKeyPath *string
|
||||
outPubPath *string
|
||||
inKeyPath *string
|
||||
curve *string
|
||||
version *uint
|
||||
pqSuite *string
|
||||
p11url *string
|
||||
}
|
||||
|
||||
@@ -27,6 +30,9 @@ func newKeygenFlags() *keygenFlags {
|
||||
cf.outPubPath = cf.set.String("out-pub", "", "Required: path to write the public key to")
|
||||
cf.outKeyPath = cf.set.String("out-key", "", "Required: path to write the private key to")
|
||||
cf.curve = cf.set.String("curve", defaultCurve(), "ECDH Curve (25519, P256)")
|
||||
cf.version = cf.set.Uint("version", 0, "Optional: 3 adds a post-quantum key, for version 3 certificates")
|
||||
cf.inKeyPath = cf.set.String("in-key", "", "Optional: path to an existing private key to add a post-quantum key to, keeping the existing key. Implies -version 3")
|
||||
cf.pqSuite = pqSuiteFlag(cf.set, "Optional: post-quantum suite of a version 3 key, which must be the suite of the CA that signs it")
|
||||
cf.p11url = p11Flag(cf.set)
|
||||
return &cf
|
||||
}
|
||||
@@ -51,9 +57,45 @@ func keygen(args []string, out io.Writer, errOut io.Writer) error {
|
||||
return err
|
||||
}
|
||||
|
||||
version := cert.Version(*cf.version)
|
||||
if *cf.inKeyPath != "" {
|
||||
version = cert.Version3
|
||||
}
|
||||
if version != 0 && version != cert.Version3 {
|
||||
return newHelpErrorf("-version must be %v, or left out for keys that work with any other version", cert.Version3)
|
||||
}
|
||||
if version == cert.Version3 && isP11 {
|
||||
return newHelpErrorf("-version 3 can not be used with -pkcs11, the post-quantum key has to be in out-key")
|
||||
}
|
||||
suite, err := parsePQSuiteFlag(cf.set, *cf.pqSuite, version == cert.Version3, "is only for -version 3")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var claims ioClaims
|
||||
if err := reserveInputs(&claims, "in-key", *cf.inKeyPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var pub, rawPriv []byte
|
||||
var curve cert.Curve
|
||||
if isP11 {
|
||||
if *cf.inKeyPath != "" {
|
||||
raw, err := readInput("in-key", *cf.inKeyPath, &claims)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while reading in-key: %s", err)
|
||||
}
|
||||
rawPriv, _, curve, err = cert.UnmarshalPrivateKeyFromPEM(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while parsing in-key: %s", err)
|
||||
}
|
||||
pub, err = publicKeyFor(curve, rawPriv)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while parsing in-key: %s", err)
|
||||
}
|
||||
if fips140.Enforced() && curve == cert.Curve_CURVE25519 {
|
||||
return errors.New("use of Curve25519 is not allowed in FIPS 140-only mode")
|
||||
}
|
||||
} else if isP11 {
|
||||
switch *cf.curve {
|
||||
case "P256":
|
||||
curve = cert.Curve_P256
|
||||
@@ -76,7 +118,13 @@ func keygen(args []string, out io.Writer, errOut io.Writer) error {
|
||||
}
|
||||
}
|
||||
|
||||
var claims ioClaims
|
||||
if version == cert.Version3 {
|
||||
pub, rawPriv, err = appendPQKey(suite, pub, rawPriv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := reserveOutputs(&claims,
|
||||
"out-key", *cf.outKeyPath,
|
||||
"out-pub", *cf.outPubPath,
|
||||
@@ -97,12 +145,20 @@ func keygen(args []string, out io.Writer, errOut io.Writer) error {
|
||||
return fmt.Errorf("error while getting public key: %w", err)
|
||||
}
|
||||
} else {
|
||||
err = writeOutput(*cf.outKeyPath, cert.MarshalPrivateKeyToPEM(curve, rawPriv), 0600, out)
|
||||
b := cert.MarshalPrivateKeyToPEM(curve, rawPriv)
|
||||
if version == cert.Version3 {
|
||||
b = cert.MarshalPQPrivateKeyToPEM(curve, suite, rawPriv)
|
||||
}
|
||||
err = writeOutput(*cf.outKeyPath, b, 0600, out)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while writing out-key: %s", err)
|
||||
}
|
||||
}
|
||||
err = writeOutput(*cf.outPubPath, cert.MarshalPublicKeyToPEM(curve, pub), 0600, out)
|
||||
b := cert.MarshalPublicKeyToPEM(curve, pub)
|
||||
if version == cert.Version3 {
|
||||
b = cert.MarshalPQPublicKeyToPEM(curve, suite, pub)
|
||||
}
|
||||
err = writeOutput(*cf.outPubPath, b, 0600, out)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while writing out-pub: %s", err)
|
||||
}
|
||||
|
||||
@@ -23,11 +23,17 @@ func Test_keygenHelp(t *testing.T) {
|
||||
" Pass \"-\" to any path flag to read from stdin or write to stdout.\n"+
|
||||
" -curve string\n"+
|
||||
" \tECDH Curve (25519, P256) (default \"25519\")\n"+
|
||||
" -in-key string\n"+
|
||||
" \tOptional: path to an existing private key to add a post-quantum key to, keeping the existing key. Implies -version 3\n"+
|
||||
" -out-key string\n"+
|
||||
" \tRequired: path to write the private key to\n"+
|
||||
" -out-pub string\n"+
|
||||
" \tRequired: path to write the public key to\n"+
|
||||
optionalPkcs11String(" -pkcs11 string\n \tOptional: PKCS#11 URI to an existing private key\n"),
|
||||
optionalPkcs11String(" -pkcs11 string\n \tOptional: PKCS#11 URI to an existing private key\n")+
|
||||
" -pq-suite string\n"+
|
||||
" \tOptional: post-quantum suite of a version 3 key, which must be the suite of the CA that signs it (MLKEM1024_MLDSA87) (default \"MLKEM1024_MLDSA87\")\n"+
|
||||
" -version uint\n"+
|
||||
" \tOptional: 3 adds a post-quantum key, for version 3 certificates\n",
|
||||
ob.String(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -89,6 +89,8 @@ func main() {
|
||||
err = printCert(args[1:], os.Stdout, os.Stderr)
|
||||
case "verify":
|
||||
err = verify(args[1:], os.Stdout, os.Stderr)
|
||||
case "pq-extend":
|
||||
err = pqExtend(args[1:], os.Stdout, os.Stderr, StdinPasswordReader{})
|
||||
default:
|
||||
err = fmt.Errorf("unknown mode: %s", args[0])
|
||||
}
|
||||
@@ -122,6 +124,8 @@ func handleError(mode string, e error, out io.Writer) int {
|
||||
printHelp(out)
|
||||
case "verify":
|
||||
verifyHelp(out)
|
||||
case "pq-extend":
|
||||
pqExtendHelp(out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +149,7 @@ func help(err string, out io.Writer) {
|
||||
fmt.Fprintln(out, " "+signSummary())
|
||||
fmt.Fprintln(out, " "+printSummary())
|
||||
fmt.Fprintln(out, " "+verifySummary())
|
||||
fmt.Fprintln(out, " "+pqExtendSummary())
|
||||
fmt.Fprintln(out, "")
|
||||
fmt.Fprintf(out, " To see usage for a given mode, use %s <mode> -h\n", os.Args[0])
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ func Test_help(t *testing.T) {
|
||||
" " + signSummary() + "\n" +
|
||||
" " + printSummary() + "\n" +
|
||||
" " + verifySummary() + "\n" +
|
||||
" " + pqExtendSummary() + "\n" +
|
||||
"\n" +
|
||||
" To see usage for a given mode, use " + os.Args[0] + " <mode> -h\n"
|
||||
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"encoding/pem"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
)
|
||||
|
||||
// pqSuiteFlag adds -pq-suite to a flag set.
|
||||
func pqSuiteFlag(set *flag.FlagSet, usage string) *string {
|
||||
var names []string
|
||||
for _, s := range cert.PQSuites() {
|
||||
names = append(names, s.String())
|
||||
}
|
||||
return set.String("pq-suite", cert.DefaultPQSuite.String(), usage+" ("+strings.Join(names, ", ")+")")
|
||||
}
|
||||
|
||||
// parsePQSuiteFlag returns the suite -pq-suite names. Setting it is an error unless allowed, when the suite has no use
|
||||
// or comes from elsewhere.
|
||||
func parsePQSuiteFlag(set *flag.FlagSet, value string, allowed bool, why string) (cert.PQSuite, error) {
|
||||
given := false
|
||||
set.Visit(func(f *flag.Flag) {
|
||||
if f.Name == "pq-suite" {
|
||||
given = true
|
||||
}
|
||||
})
|
||||
if given && !allowed {
|
||||
return cert.PQSuiteUnknown, newHelpErrorf("-pq-suite %s", why)
|
||||
}
|
||||
s, err := cert.ParsePQSuite(value)
|
||||
if err != nil {
|
||||
return cert.PQSuiteUnknown, newHelpErrorf("-pq-suite: %s", err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// appendPQSigningKey makes a classical CA keypair into a version 3 composite one with a fresh key of suite.
|
||||
func appendPQSigningKey(suite cert.PQSuite, pub, priv []byte) ([]byte, []byte, error) {
|
||||
pqPub, pqPriv, err := suite.GenerateKey(true)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("error while generating %v CA key: %s", suite, err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...), nil
|
||||
}
|
||||
|
||||
// appendPQKey makes a classical host keypair into a version 3 composite one with a fresh key of suite.
|
||||
func appendPQKey(suite cert.PQSuite, pub, priv []byte) ([]byte, []byte, error) {
|
||||
pqPub, pqPriv, err := suite.GenerateKey(false)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("error while generating %v key: %s", suite, err)
|
||||
}
|
||||
return append(pub, pqPub...), append(priv, pqPriv...), nil
|
||||
}
|
||||
|
||||
// publicKeyFor returns the public key of a classical host private key.
|
||||
func publicKeyFor(curve cert.Curve, priv []byte) ([]byte, error) {
|
||||
var c ecdh.Curve
|
||||
switch curve {
|
||||
case cert.Curve_CURVE25519:
|
||||
c = ecdh.X25519()
|
||||
case cert.Curve_P256:
|
||||
c = ecdh.P256()
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid curve: %s", curve)
|
||||
}
|
||||
k, err := c.NewPrivateKey(priv)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("not a classical %s private key, it may already have a post-quantum key", curve)
|
||||
}
|
||||
return k.PublicKey().Bytes(), nil
|
||||
}
|
||||
|
||||
type pqExtendFlags struct {
|
||||
set *flag.FlagSet
|
||||
caKeyPath *string
|
||||
caCertPath *string
|
||||
inCertPath *string
|
||||
inPubPath *string
|
||||
outCertPath *string
|
||||
outKeyPath *string
|
||||
pqSuite *string
|
||||
}
|
||||
|
||||
func newPQExtendFlags() *pqExtendFlags {
|
||||
pf := pqExtendFlags{set: flag.NewFlagSet("pq-extend", flag.ContinueOnError)}
|
||||
pf.set.Usage = func() {}
|
||||
pf.inCertPath = pf.set.String("in-crt", "", "Required: path to the version 2 certificate to extend, a CA or a host")
|
||||
pf.outCertPath = pf.set.String("out-crt", "", "Required: path to write the version 3 certificate to")
|
||||
pf.caKeyPath = pf.set.String("ca-key", "ca.key", "Optional: path to the CA key. For a CA in-crt, its own version 2 key. For a host in-crt, the version 3 key of the CA that issued it")
|
||||
pf.caCertPath = pf.set.String("ca-crt", "", "Required for a host in-crt: path to the version 3 form of the CA that issued it")
|
||||
pf.inPubPath = pf.set.String("in-pub", "", "Required for a host in-crt: path to the host's public key from keygen -in-key")
|
||||
pf.outKeyPath = pf.set.String("out-key", "", "Required for a CA in-crt: path to write the CA's version 3 key to, encrypted again if ca-key was")
|
||||
pf.pqSuite = pqSuiteFlag(pf.set, "Optional, for a CA in-crt: post-quantum suite of the version 3 CA. A host takes its CA's suite")
|
||||
return &pf
|
||||
}
|
||||
|
||||
// pqExtend turns a version 2 certificate into a version 3 one in place: the v2 form, and so its fingerprint and
|
||||
// existing trust in it, stays exactly as it was.
|
||||
func pqExtend(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
|
||||
pf := newPQExtendFlags()
|
||||
if err := pf.set.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mustFlagString("in-crt", pf.inCertPath); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mustFlagString("out-crt", pf.outCertPath); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := mustFlagString("ca-key", pf.caKeyPath); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var claims ioClaims
|
||||
if err := reserveInputs(&claims,
|
||||
"in-crt", *pf.inCertPath,
|
||||
"ca-key", *pf.caKeyPath,
|
||||
"ca-crt", *pf.caCertPath,
|
||||
"in-pub", *pf.inPubPath,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := reserveOutputs(&claims,
|
||||
"out-crt", *pf.outCertPath,
|
||||
"out-key", *pf.outKeyPath,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rawCert, err := readInput("in-crt", *pf.inCertPath, &claims)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while reading in-crt: %s", err)
|
||||
}
|
||||
c, _, err := cert.UnmarshalCertificateFromPEM(rawCert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while parsing in-crt: %s", err)
|
||||
}
|
||||
if c.Version() != cert.Version2 {
|
||||
return fmt.Errorf("only version 2 certificates extend to version 3, in-crt is version %d", c.Version())
|
||||
}
|
||||
|
||||
for _, p := range []string{*pf.outCertPath, *pf.outKeyPath} {
|
||||
if p != "" && !isStdio(p) {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
return fmt.Errorf("refusing to overwrite existing file: %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rawCAKey, err := readInput("ca-key", *pf.caKeyPath, &claims)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while reading ca-key: %s", err)
|
||||
}
|
||||
curve, caKey, passphrase, err := readSigningKey(rawCAKey, errOut, pr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
suite, err := parsePQSuiteFlag(pf.set, *pf.pqSuite, c.IsCA(), "is for CA certificates, a host takes its CA's suite")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var c3 cert.Certificate
|
||||
if c.IsCA() {
|
||||
c3, err = extendCA(pf, c, suite, curve, caKey, rawCAKey, passphrase, out)
|
||||
} else {
|
||||
c3, err = extendHost(pf, c, curve, caKey, &claims)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b, err := c3.MarshalPEM()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while marshalling certificate: %s", err)
|
||||
}
|
||||
if err := writeOutput(*pf.outCertPath, b, 0600, out); err != nil {
|
||||
return fmt.Errorf("error while writing out-crt: %s", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// extendCA gives a v2 CA a post-quantum key of suite and writes out the composite key.
|
||||
func extendCA(pf *pqExtendFlags, ca cert.Certificate, suite cert.PQSuite, curve cert.Curve, key, rawKey, passphrase []byte, out io.Writer) (cert.Certificate, error) {
|
||||
if *pf.caCertPath != "" || *pf.inPubPath != "" {
|
||||
return nil, newHelpErrorf("-ca-crt and -in-pub are for host certificates, a CA extends itself")
|
||||
}
|
||||
if err := mustFlagString("out-key", pf.outKeyPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ca.VerifyPrivateKey(curve, key); err != nil {
|
||||
return nil, fmt.Errorf("refusing to extend, the CA certificate does not match ca-key")
|
||||
}
|
||||
|
||||
pub, priv, err := appendPQSigningKey(suite, nil, append([]byte(nil), key...))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signPQ, err := cert.SignPQ(suite, priv[len(key):])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c3, err := cert.ExtendToV3(ca, suite, pub, nil, signPQ)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while extending: %s", err)
|
||||
}
|
||||
|
||||
var b []byte
|
||||
if passphrase != nil {
|
||||
// Encrypt it the way ca-key was, with a fresh salt.
|
||||
block, _ := pem.Decode(rawKey)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("error while parsing ca-key: input did not contain a valid PEM encoded block")
|
||||
}
|
||||
ned, err := cert.UnmarshalNebulaEncryptedData(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while parsing encrypted ca-key: %s", err)
|
||||
}
|
||||
a := ned.EncryptionMetadata.Argon2Parameters
|
||||
kdf := cert.NewArgon2Parameters(a.Memory, a.Parallelism, a.Iterations)
|
||||
b, err = cert.EncryptAndMarshalPQSigningPrivateKey(curve, suite, priv, passphrase, kdf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while encrypting out-key: %s", err)
|
||||
}
|
||||
} else {
|
||||
b = cert.MarshalPQSigningPrivateKeyToPEM(curve, suite, priv)
|
||||
}
|
||||
if err := writeOutput(*pf.outKeyPath, b, 0600, out); err != nil {
|
||||
return nil, fmt.Errorf("error while writing out-key: %s", err)
|
||||
}
|
||||
return c3, nil
|
||||
}
|
||||
|
||||
// extendHost adds a host's post-quantum key to its certificate, signed by the v3 form of its CA, in the CA's suite.
|
||||
func extendHost(pf *pqExtendFlags, c cert.Certificate, curve cert.Curve, caKey []byte, claims *ioClaims) (cert.Certificate, error) {
|
||||
if *pf.outKeyPath != "" {
|
||||
return nil, newHelpErrorf("-out-key is for CA certificates, a host's key comes from keygen -in-key")
|
||||
}
|
||||
if err := mustFlagString("ca-crt", pf.caCertPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := mustFlagString("in-pub", pf.inPubPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rawCA, err := readInput("ca-crt", *pf.caCertPath, claims)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while reading ca-crt: %s", err)
|
||||
}
|
||||
ca, _, err := cert.UnmarshalCertificateFromPEM(rawCA)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while parsing ca-crt: %s", err)
|
||||
}
|
||||
if ca.Version() != cert.Version3 {
|
||||
return nil, fmt.Errorf("ca-crt must be a version 3 CA, extend the CA first")
|
||||
}
|
||||
if err := ca.VerifyPrivateKey(curve, caKey); err != nil {
|
||||
return nil, fmt.Errorf("refusing to extend, ca-crt does not match ca-key")
|
||||
}
|
||||
|
||||
rawPub, err := readInput("in-pub", *pf.inPubPath, claims)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while reading in-pub: %s", err)
|
||||
}
|
||||
pub, _, pubCurve, err := cert.UnmarshalPublicKeyFromPEM(rawPub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while parsing in-pub: %s", err)
|
||||
}
|
||||
suite := cert.PQSuiteOf(ca)
|
||||
classical, pq, err := suite.SplitPublicKey(false, pub)
|
||||
if pubCurve != c.Curve() || err != nil {
|
||||
return nil, fmt.Errorf("in-pub must be the host's key from keygen -in-key -pq-suite %v", suite)
|
||||
}
|
||||
if !bytes.Equal(classical, c.PublicKey()) {
|
||||
return nil, fmt.Errorf("in-pub does not extend the key in in-crt")
|
||||
}
|
||||
|
||||
_, pqCAKey, err := suite.SplitPrivateKey(true, caKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
signPQ, err := cert.SignPQ(suite, pqCAKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c3, err := cert.ExtendToV3(c, suite, pq, ca, signPQ)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error while extending: %s", err)
|
||||
}
|
||||
return c3, nil
|
||||
}
|
||||
|
||||
func pqExtendSummary() string {
|
||||
return "pq-extend <flags>: extend a version 2 CA or host certificate to version 3 in place, keeping its v2 form and fingerprint"
|
||||
}
|
||||
|
||||
func pqExtendHelp(out io.Writer) {
|
||||
pf := newPQExtendFlags()
|
||||
out.Write([]byte("Usage of " + os.Args[0] + " " + pqExtendSummary() + "\n"))
|
||||
out.Write([]byte(stdioHelpText))
|
||||
pf.set.SetOutput(out)
|
||||
pf.set.PrintDefaults()
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func readCert(t *testing.T, path string) cert.Certificate {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
c, _, err := cert.UnmarshalCertificateFromPEM(b)
|
||||
require.NoError(t, err)
|
||||
return c
|
||||
}
|
||||
|
||||
func readSigningKeyFile(t *testing.T, path string) (cert.Curve, []byte) {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
k, _, curve, err := cert.UnmarshalSigningPrivateKeyFromPEM(b)
|
||||
require.NoError(t, err)
|
||||
return curve, k
|
||||
}
|
||||
|
||||
func readKeyFile(t *testing.T, path string) (cert.Curve, []byte) {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
k, _, curve, err := cert.UnmarshalPrivateKeyFromPEM(b)
|
||||
require.NoError(t, err)
|
||||
return curve, k
|
||||
}
|
||||
|
||||
func verifiedBy(t *testing.T, c cert.Certificate, cas ...cert.Certificate) error {
|
||||
t.Helper()
|
||||
pool := cert.NewCAPool()
|
||||
for _, ca := range cas {
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
}
|
||||
_, err := pool.VerifyCertificate(time.Now(), c)
|
||||
return err
|
||||
}
|
||||
|
||||
func TestPQ_CAAndSign(t *testing.T) {
|
||||
for _, curve := range []string{"25519", "P256"} {
|
||||
t.Run(curve, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ob, eb := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
nopw := &StubPasswordReader{}
|
||||
p := func(n string) string { return filepath.Join(dir, n) }
|
||||
|
||||
require.NoError(t, ca([]string{"-version", "3", "-curve", curve, "-name", "pq ca", "-out-crt", p("ca.crt"), "-out-key", p("ca.key")}, ob, eb, nopw))
|
||||
caCrt := readCert(t, p("ca.crt"))
|
||||
assert.Equal(t, cert.Version3, caCrt.Version())
|
||||
caCurve, caKey := readSigningKeyFile(t, p("ca.key"))
|
||||
require.NoError(t, caCrt.VerifyPrivateKey(caCurve, caKey))
|
||||
|
||||
// A v3 CA signs v3 by default.
|
||||
require.NoError(t, signCert([]string{"-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "host", "-networks", "10.1.0.1/16", "-out-crt", p("host.crt"), "-out-key", p("host.key")}, ob, eb, nopw))
|
||||
host := readCert(t, p("host.crt"))
|
||||
assert.Equal(t, cert.Version3, host.Version())
|
||||
hostCurve, hostKey := readKeyFile(t, p("host.key"))
|
||||
require.NoError(t, host.VerifyPrivateKey(hostCurve, hostKey))
|
||||
require.NoError(t, verifiedBy(t, host, caCrt))
|
||||
|
||||
// And v2 as its v2 form.
|
||||
require.NoError(t, signCert([]string{"-version", "2", "-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "old", "-networks", "10.1.0.2/16", "-out-crt", p("old.crt"), "-out-key", p("old.key")}, ob, eb, nopw))
|
||||
old := readCert(t, p("old.crt"))
|
||||
assert.Equal(t, cert.Version2, old.Version())
|
||||
require.NoError(t, verifiedBy(t, old, cert.V2Form(caCrt)))
|
||||
|
||||
// keygen -version 3 makes keys for v3 certificates, and only those.
|
||||
require.NoError(t, keygen([]string{"-version", "3", "-curve", curve, "-out-key", p("k3.key"), "-out-pub", p("k3.pub")}, ob, eb))
|
||||
require.NoError(t, signCert([]string{"-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "k3", "-networks", "10.1.0.3/16", "-in-pub", p("k3.pub"), "-out-crt", p("k3.crt")}, ob, eb, nopw))
|
||||
_, k3 := readKeyFile(t, p("k3.key"))
|
||||
require.NoError(t, readCert(t, p("k3.crt")).VerifyPrivateKey(hostCurve, k3))
|
||||
require.ErrorContains(t, signCert([]string{"-version", "2", "-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "x", "-networks", "10.1.0.4/16", "-in-pub", p("k3.pub"), "-out-crt", p("x.crt")}, ob, eb, nopw), "only version 3 certificates carry")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPQ_SignErrors(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ob, eb := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
nopw := &StubPasswordReader{}
|
||||
p := func(n string) string { return filepath.Join(dir, n) }
|
||||
|
||||
require.NoError(t, ca([]string{"-name", "v2 ca", "-out-crt", p("ca.crt"), "-out-key", p("ca.key")}, ob, eb, nopw))
|
||||
require.ErrorContains(t, signCert([]string{"-version", "3", "-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "h", "-networks", "10.1.0.1/16", "-out-crt", p("h.crt"), "-out-key", p("h.key")}, ob, eb, nopw), "must be signed by a version 3 CA")
|
||||
|
||||
require.NoError(t, keygen([]string{"-out-key", p("k.key"), "-out-pub", p("k.pub")}, ob, eb))
|
||||
require.NoError(t, ca([]string{"-version", "3", "-name", "v3 ca", "-out-crt", p("ca3.crt"), "-out-key", p("ca3.key")}, ob, eb, nopw))
|
||||
require.ErrorContains(t, signCert([]string{"-ca-crt", p("ca3.crt"), "-ca-key", p("ca3.key"), "-name", "h", "-networks", "10.1.0.1/16", "-in-pub", p("k.pub"), "-out-crt", p("h3.crt")}, ob, eb, nopw), "need an in-pub from keygen -version 3")
|
||||
|
||||
// keygen -in-key refuses a key that already has a post-quantum key.
|
||||
require.NoError(t, keygen([]string{"-version", "3", "-out-key", p("k3.key"), "-out-pub", p("k3.pub")}, ob, eb))
|
||||
require.ErrorContains(t, keygen([]string{"-in-key", p("k3.key"), "-out-key", p("k33.key"), "-out-pub", p("k33.pub")}, ob, eb), "already have a post-quantum key")
|
||||
}
|
||||
|
||||
func TestPQ_SuiteFlag(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ob, eb := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
nopw := &StubPasswordReader{}
|
||||
p := func(n string) string { return filepath.Join(dir, n) }
|
||||
|
||||
// The suite can be named, case aside, and the certificates a CA signs share its suite.
|
||||
require.NoError(t, ca([]string{"-version", "3", "-pq-suite", "mlkem1024_mldsa87", "-name", "ca", "-out-crt", p("ca.crt"), "-out-key", p("ca.key")}, ob, eb, nopw))
|
||||
assert.Equal(t, cert.PQSuite_MLKEM1024_MLDSA87, cert.PQSuiteOf(readCert(t, p("ca.crt"))))
|
||||
require.NoError(t, keygen([]string{"-version", "3", "-pq-suite", "MLKEM1024_MLDSA87", "-out-key", p("k.key"), "-out-pub", p("k.pub")}, ob, eb))
|
||||
require.NoError(t, signCert([]string{"-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "h", "-networks", "10.1.0.1/16", "-in-pub", p("k.pub"), "-out-crt", p("h.crt")}, ob, eb, nopw))
|
||||
assert.Equal(t, cert.PQSuite_MLKEM1024_MLDSA87, cert.PQSuiteOf(readCert(t, p("h.crt"))))
|
||||
|
||||
// Printing shows it.
|
||||
ob.Reset()
|
||||
require.NoError(t, printCert([]string{"-json", "-path", p("h.crt")}, ob, eb))
|
||||
assert.Contains(t, ob.String(), `"pqSuite":"MLKEM1024_MLDSA87"`)
|
||||
|
||||
// Unknown suites, and suites where there is no post-quantum key, are refused.
|
||||
require.ErrorContains(t, ca([]string{"-version", "3", "-pq-suite", "mlkem768_mldsa65", "-name", "x", "-out-crt", p("x.crt"), "-out-key", p("x.key")}, ob, eb, nopw), "unknown post-quantum suite")
|
||||
require.ErrorContains(t, ca([]string{"-pq-suite", "MLKEM1024_MLDSA87", "-name", "x", "-out-crt", p("x.crt"), "-out-key", p("x.key")}, ob, eb, nopw), "only for -version 3")
|
||||
require.ErrorContains(t, keygen([]string{"-pq-suite", "MLKEM1024_MLDSA87", "-out-key", p("x.key"), "-out-pub", p("x.pub")}, ob, eb), "only for -version 3")
|
||||
|
||||
// A host takes its CA's suite when extended.
|
||||
require.NoError(t, ca([]string{"-name", "ca2", "-out-crt", p("ca2.crt"), "-out-key", p("ca2.key")}, ob, eb, nopw))
|
||||
require.NoError(t, signCert([]string{"-ca-crt", p("ca2.crt"), "-ca-key", p("ca2.key"), "-name", "h2", "-networks", "10.1.0.2/16", "-out-crt", p("h2.crt"), "-out-key", p("h2.key")}, ob, eb, nopw))
|
||||
require.NoError(t, pqExtend([]string{"-in-crt", p("ca2.crt"), "-ca-key", p("ca2.key"), "-pq-suite", "MLKEM1024_MLDSA87", "-out-crt", p("ca23.crt"), "-out-key", p("ca23.key")}, ob, eb, nopw))
|
||||
require.NoError(t, keygen([]string{"-in-key", p("h2.key"), "-out-key", p("h23.key"), "-out-pub", p("h23.pub")}, ob, eb))
|
||||
require.ErrorContains(t, pqExtend([]string{"-in-crt", p("h2.crt"), "-in-pub", p("h23.pub"), "-ca-crt", p("ca23.crt"), "-ca-key", p("ca23.key"), "-pq-suite", "MLKEM1024_MLDSA87", "-out-crt", p("h23.crt")}, ob, eb, nopw), "a host takes its CA's suite")
|
||||
}
|
||||
|
||||
// TestPQ_Extend upgrades a v2 CA and a host in place, the way a running network migrates.
|
||||
func TestPQ_Extend(t *testing.T) {
|
||||
for _, encrypt := range []bool{false, true} {
|
||||
name := "plain"
|
||||
if encrypt {
|
||||
name = "encrypted"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
ob, eb := &bytes.Buffer{}, &bytes.Buffer{}
|
||||
pw := &StubPasswordReader{}
|
||||
if encrypt {
|
||||
t.Setenv("NEBULA_CA_PASSPHRASE", "hunter2")
|
||||
}
|
||||
p := func(n string) string { return filepath.Join(dir, n) }
|
||||
|
||||
caArgs := []string{"-name", "ca", "-out-crt", p("ca.crt"), "-out-key", p("ca.key"), "-argon-memory", "1024"}
|
||||
if encrypt {
|
||||
caArgs = append(caArgs, "-encrypt")
|
||||
}
|
||||
require.NoError(t, ca(caArgs, ob, eb, pw))
|
||||
require.NoError(t, signCert([]string{"-ca-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-name", "host", "-networks", "10.1.0.1/16", "-out-crt", p("host.crt"), "-out-key", p("host.key")}, ob, eb, pw))
|
||||
ca2 := readCert(t, p("ca.crt"))
|
||||
host2 := readCert(t, p("host.crt"))
|
||||
|
||||
// The CA extends itself.
|
||||
require.NoError(t, pqExtend([]string{"-in-crt", p("ca.crt"), "-ca-key", p("ca.key"), "-out-crt", p("ca3.crt"), "-out-key", p("ca3.key")}, ob, eb, pw))
|
||||
ca3 := readCert(t, p("ca3.crt"))
|
||||
assert.Equal(t, cert.Version3, ca3.Version())
|
||||
assertSameCert(t, ca2, cert.V2Form(ca3))
|
||||
raw, err := os.ReadFile(p("ca3.key"))
|
||||
require.NoError(t, err)
|
||||
curve, ca3Key, _, err := readSigningKey(raw, eb, pw)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, ca3.VerifyPrivateKey(curve, ca3Key))
|
||||
if encrypt {
|
||||
_, _, _, err = cert.UnmarshalSigningPrivateKeyFromPEM(raw)
|
||||
require.ErrorIs(t, err, cert.ErrPrivateKeyEncrypted, "an encrypted ca-key stays encrypted")
|
||||
}
|
||||
|
||||
// The host gets a post-quantum key on top of the one it has, and the CA signs it.
|
||||
require.NoError(t, keygen([]string{"-in-key", p("host.key"), "-out-key", p("host3.key"), "-out-pub", p("host3.pub")}, ob, eb))
|
||||
require.NoError(t, pqExtend([]string{"-in-crt", p("host.crt"), "-in-pub", p("host3.pub"), "-ca-crt", p("ca3.crt"), "-ca-key", p("ca3.key"), "-out-crt", p("host3.crt")}, ob, eb, pw))
|
||||
host3 := readCert(t, p("host3.crt"))
|
||||
assert.Equal(t, cert.Version3, host3.Version())
|
||||
assertSameCert(t, host2, cert.V2Form(host3))
|
||||
hostCurve, host3Key := readKeyFile(t, p("host3.key"))
|
||||
require.NoError(t, host3.VerifyPrivateKey(hostCurve, host3Key))
|
||||
require.NoError(t, verifiedBy(t, host3, ca3))
|
||||
require.NoError(t, verifiedBy(t, host2, ca2), "existing trust is untouched")
|
||||
|
||||
// print leads a version 3 certificate with both fingerprints and says which one blocks both forms.
|
||||
ob.Reset()
|
||||
require.NoError(t, printCert([]string{"-path", p("host3.crt")}, ob, eb))
|
||||
fp3, err := host3.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
fp2, err := host2.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
printed := ob.String()
|
||||
lead := "Fingerprint: " + fp3 + "\nv2 fingerprint: " + fp2 + " (block this one in pki.blocklist, it covers both forms)\n"
|
||||
require.Greater(t, len(printed), len(lead))
|
||||
assert.Equal(t, lead, printed[:len(lead)])
|
||||
|
||||
// Someone else's key does not extend this host.
|
||||
require.NoError(t, keygen([]string{"-version", "3", "-out-key", p("other.key"), "-out-pub", p("other.pub")}, ob, eb))
|
||||
require.ErrorContains(t, pqExtend([]string{"-in-crt", p("host.crt"), "-in-pub", p("other.pub"), "-ca-crt", p("ca3.crt"), "-ca-key", p("ca3.key"), "-out-crt", p("bad.crt")}, ob, eb, pw), "does not extend the key")
|
||||
|
||||
// Nor does the v2 CA key, or a v3 certificate.
|
||||
require.ErrorContains(t, pqExtend([]string{"-in-crt", p("host.crt"), "-in-pub", p("host3.pub"), "-ca-crt", p("ca3.crt"), "-ca-key", p("ca.key"), "-out-crt", p("bad.crt")}, ob, eb, pw), "does not match ca-key")
|
||||
require.ErrorContains(t, pqExtend([]string{"-in-crt", p("host3.crt"), "-in-pub", p("host3.pub"), "-ca-crt", p("ca3.crt"), "-ca-key", p("ca3.key"), "-out-crt", p("bad.crt")}, ob, eb, pw), "only version 2 certificates")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertSameCert(t *testing.T, want, got cert.Certificate) {
|
||||
t.Helper()
|
||||
wb, err := want.Marshal()
|
||||
require.NoError(t, err)
|
||||
gb, err := got.Marshal()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, wb, gb)
|
||||
}
|
||||
@@ -73,6 +73,19 @@ func printCert(args []string, out io.Writer, errOut io.Writer) error {
|
||||
if *pf.json {
|
||||
jsonCerts = append(jsonCerts, c)
|
||||
} else {
|
||||
// A version 3 certificate has two fingerprints, and only the v2 one blocks both of its forms.
|
||||
// Lead with them so the right one is the obvious one to copy.
|
||||
if v2 := cert.V2Form(c); v2 != nil {
|
||||
fp, err := c.Fingerprint()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while computing fingerprint: %s", err)
|
||||
}
|
||||
v2fp, err := v2.Fingerprint()
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while computing v2 fingerprint: %s", err)
|
||||
}
|
||||
_, _ = fmt.Fprintf(out, "Fingerprint: %s\nv2 fingerprint: %s (block this one in pki.blocklist, it covers both forms)\n", fp, v2fp)
|
||||
}
|
||||
_, _ = out.Write([]byte(c.String()))
|
||||
_, _ = out.Write([]byte("\n"))
|
||||
}
|
||||
|
||||
+105
-35
@@ -44,7 +44,7 @@ type signFlags struct {
|
||||
func newSignFlags() *signFlags {
|
||||
sf := signFlags{set: flag.NewFlagSet("sign", flag.ContinueOnError)}
|
||||
sf.set.Usage = func() {}
|
||||
sf.version = sf.set.Uint("version", 0, "Optional: version of the certificate format to use. The default is to match the version of the signing CA")
|
||||
sf.version = sf.set.Uint("version", 0, "Optional: version of the certificate format to use. The default is to match the version of the signing CA. A version 3 CA also signs version 2 certificates, as its v2 form")
|
||||
sf.caKeyPath = sf.set.String("ca-key", "ca.key", "Optional: path to the signing CA key")
|
||||
sf.caCertPath = sf.set.String("ca-crt", "ca.crt", "Optional: path to the signing CA cert")
|
||||
sf.name = sf.set.String("name", "", "Required: name of the cert, usually a hostname")
|
||||
@@ -102,8 +102,8 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
}
|
||||
|
||||
version := cert.Version(*sf.version)
|
||||
if version != 0 && version != cert.Version1 && version != cert.Version2 {
|
||||
return newHelpErrorf("-version must be either %v or %v", cert.Version1, cert.Version2)
|
||||
if version != 0 && version != cert.Version1 && version != cert.Version2 && version != cert.Version3 {
|
||||
return newHelpErrorf("-version must be %v, %v or %v", cert.Version1, cert.Version2, cert.Version3)
|
||||
}
|
||||
|
||||
if *sf.outKeyPath == "" {
|
||||
@@ -139,37 +139,9 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
return fmt.Errorf("error while reading ca-key: %s", err)
|
||||
}
|
||||
|
||||
// naively attempt to decode the private key as though it is not encrypted
|
||||
caKey, _, curve, err = cert.UnmarshalSigningPrivateKeyFromPEM(rawCAKey)
|
||||
if errors.Is(err, cert.ErrPrivateKeyEncrypted) {
|
||||
var passphrase []byte
|
||||
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
||||
if len(passphrase) == 0 {
|
||||
// ask for a passphrase until we get one
|
||||
for range 5 {
|
||||
errOut.Write([]byte("Enter passphrase: "))
|
||||
passphrase, err = pr.ReadPassword()
|
||||
|
||||
if errors.Is(err, ErrNoTerminal) {
|
||||
return fmt.Errorf("ca-key is encrypted and must be decrypted interactively")
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("error reading password: %s", err)
|
||||
}
|
||||
|
||||
if len(passphrase) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(passphrase) == 0 {
|
||||
return fmt.Errorf("cannot open encrypted ca-key without passphrase")
|
||||
}
|
||||
}
|
||||
curve, caKey, _, err = cert.DecryptAndUnmarshalSigningPrivateKey(passphrase, rawCAKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while parsing encrypted ca-key: %s", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("error while parsing ca-key: %s", err)
|
||||
curve, caKey, _, err = readSigningKey(rawCAKey, errOut, pr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +169,23 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
version = caCert.Version()
|
||||
}
|
||||
|
||||
// A version 3 certificate is in the suite of its CA.
|
||||
suite := cert.PQSuiteOf(caCert)
|
||||
switch {
|
||||
case version == cert.Version3 && caCert.Version() != cert.Version3:
|
||||
return newHelpErrorf("version 3 certificates must be signed by a version 3 CA")
|
||||
case version == cert.Version3 && isP11:
|
||||
return newHelpErrorf("version 3 certificates can not be signed with -pkcs11, the post-quantum key has to be in ca-key")
|
||||
case version != cert.Version3 && caCert.Version() == cert.Version3:
|
||||
// A v3 CA signs anything older as its v2 form, with the classical half of its key.
|
||||
caCert = cert.V2Form(caCert)
|
||||
if caKey != nil {
|
||||
if caKey, _, err = suite.SplitPrivateKey(true, caKey); err != nil {
|
||||
return fmt.Errorf("error while parsing ca-key: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if no duration is given, expire one second before the root expires
|
||||
if *sf.duration <= 0 {
|
||||
*sf.duration = time.Until(caCert.NotAfter()) - time.Second*1
|
||||
@@ -287,6 +276,16 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
if pubCurve != curve {
|
||||
return fmt.Errorf("curve of in-pub does not match ca")
|
||||
}
|
||||
// Composite keys are longer than any classical one, an uncompressed P256 key being the longest.
|
||||
if isPQ := len(pub) > 65; isPQ != (version == cert.Version3) {
|
||||
if isPQ {
|
||||
return fmt.Errorf("in-pub has a post-quantum key, which only version 3 certificates carry")
|
||||
}
|
||||
return fmt.Errorf("version 3 certificates need an in-pub from keygen -version 3")
|
||||
}
|
||||
if _, _, err := suite.SplitPublicKey(false, pub); version == cert.Version3 && err != nil {
|
||||
return fmt.Errorf("in-pub is not a key for the CA's post-quantum suite, %v", suite)
|
||||
}
|
||||
} else if isP11 {
|
||||
pub, err = p11Client.GetPubKey()
|
||||
if err != nil {
|
||||
@@ -294,6 +293,12 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
}
|
||||
} else {
|
||||
pub, rawPriv = newKeypair(curve)
|
||||
if version == cert.Version3 {
|
||||
pub, rawPriv, err = appendPQKey(suite, pub, rawPriv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !isStdio(*sf.outCertPath) {
|
||||
@@ -378,6 +383,28 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
}
|
||||
|
||||
crts = append(crts, nc)
|
||||
|
||||
case cert.Version3:
|
||||
t := &cert.TBSCertificate{
|
||||
Version: cert.Version3,
|
||||
Name: *sf.name,
|
||||
Networks: append(v4Networks, v6Networks...),
|
||||
Groups: groups,
|
||||
UnsafeNetworks: append(v4UnsafeNetworks, v6UnsafeNetworks...),
|
||||
NotBefore: notBefore,
|
||||
NotAfter: notAfter,
|
||||
PublicKey: pub,
|
||||
IsCA: false,
|
||||
Curve: curve,
|
||||
PQSuite: suite,
|
||||
}
|
||||
|
||||
nc, err := t.Sign(caCert, curve, caKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while signing: %w", err)
|
||||
}
|
||||
crts = append(crts, nc)
|
||||
|
||||
default:
|
||||
// this should be unreachable
|
||||
return fmt.Errorf("invalid version: %d", version)
|
||||
@@ -390,7 +417,11 @@ func signCert(args []string, out io.Writer, errOut io.Writer, pr PasswordReader)
|
||||
}
|
||||
}
|
||||
|
||||
err = writeOutput(*sf.outKeyPath, cert.MarshalPrivateKeyToPEM(curve, rawPriv), 0600, out)
|
||||
b := cert.MarshalPrivateKeyToPEM(curve, rawPriv)
|
||||
if version == cert.Version3 {
|
||||
b = cert.MarshalPQPrivateKeyToPEM(curve, suite, rawPriv)
|
||||
}
|
||||
err = writeOutput(*sf.outKeyPath, b, 0600, out)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while writing out-key: %s", err)
|
||||
}
|
||||
@@ -470,3 +501,42 @@ func signHelp(out io.Writer) {
|
||||
sf.set.SetOutput(out)
|
||||
sf.set.PrintDefaults()
|
||||
}
|
||||
|
||||
// readSigningKey decodes a CA key, asking for its passphrase if it is encrypted.
|
||||
// The passphrase is returned too, nil for a key that was not encrypted.
|
||||
func readSigningKey(rawCAKey []byte, errOut io.Writer, pr PasswordReader) (cert.Curve, []byte, []byte, error) {
|
||||
// naively attempt to decode the private key as though it is not encrypted
|
||||
caKey, _, curve, err := cert.UnmarshalSigningPrivateKeyFromPEM(rawCAKey)
|
||||
if errors.Is(err, cert.ErrPrivateKeyEncrypted) {
|
||||
var passphrase []byte
|
||||
passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
|
||||
if len(passphrase) == 0 {
|
||||
// ask for a passphrase until we get one
|
||||
for range 5 {
|
||||
errOut.Write([]byte("Enter passphrase: "))
|
||||
passphrase, err = pr.ReadPassword()
|
||||
|
||||
if errors.Is(err, ErrNoTerminal) {
|
||||
return 0, nil, nil, fmt.Errorf("ca-key is encrypted and must be decrypted interactively")
|
||||
} else if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("error reading password: %s", err)
|
||||
}
|
||||
|
||||
if len(passphrase) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(passphrase) == 0 {
|
||||
return 0, nil, nil, fmt.Errorf("cannot open encrypted ca-key without passphrase")
|
||||
}
|
||||
}
|
||||
curve, caKey, _, err = cert.DecryptAndUnmarshalSigningPrivateKey(passphrase, rawCAKey)
|
||||
if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("error while parsing encrypted ca-key: %s", err)
|
||||
}
|
||||
return curve, caKey, passphrase, nil
|
||||
} else if err != nil {
|
||||
return 0, nil, nil, fmt.Errorf("error while parsing ca-key: %s", err)
|
||||
}
|
||||
return curve, caKey, nil, nil
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func Test_signHelp(t *testing.T) {
|
||||
" -unsafe-networks string\n"+
|
||||
" \tOptional: comma separated list of ip address and network in CIDR notation. Unsafe networks this cert can route for\n"+
|
||||
" -version uint\n"+
|
||||
" \tOptional: version of the certificate format to use. The default is to match the version of the signing CA\n",
|
||||
" \tOptional: version of the certificate format to use. The default is to match the version of the signing CA. A version 3 CA also signs version 2 certificates, as its v2 form\n",
|
||||
ob.String(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -272,7 +272,7 @@ func (cm *connectionManager) migrateRelayUsed(oldhostinfo, newhostinfo *HostInfo
|
||||
InitiatorRelayIndex: index,
|
||||
}
|
||||
|
||||
switch newhostinfo.GetCert().Certificate.Version() {
|
||||
switch protocolVersion(newhostinfo.GetCert().Certificate.Version()) {
|
||||
case cert.Version1:
|
||||
if !relayFrom.Is4() {
|
||||
cm.l.Error("can not migrate v1 relay with a v6 network because the relay is not running a current nebula version")
|
||||
|
||||
@@ -92,6 +92,14 @@ func (cs *ConnectionState) NextMessageCounter() (uint64, bool) {
|
||||
return c, true
|
||||
}
|
||||
|
||||
// heardFromPeer reports whether anything from the peer has decrypted under these
|
||||
// keys, beyond the handshake messages the replay window was seeded with.
|
||||
func (cs *ConnectionState) heardFromPeer(handshakeMessages uint64) bool {
|
||||
cs.decryptLock.Lock()
|
||||
defer cs.decryptLock.Unlock()
|
||||
return cs.window.current > handshakeMessages
|
||||
}
|
||||
|
||||
func (cs *ConnectionState) Curve() cert.Curve {
|
||||
return cs.myCert.Curve()
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
|
||||
+309
-90
@@ -1,15 +1,17 @@
|
||||
# Post-quantum handshakes
|
||||
|
||||
Status: draft. Decisions below were made on 2026-10-13; open items are listed at the end.
|
||||
Phase 1 is implemented (see [Implementation](#implementation-phase-1)).
|
||||
Status: draft. Decisions below were made on 2026-10-13 and 2026-10-14; open items are listed at
|
||||
the end. Post-quantum handshakes ship hybrid only, on version 3 certificates (decided
|
||||
2026-10-14); see [Implementation](#implementation-certificates-and-the-hybrid-handshake).
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Confidentiality against harvest-now-decrypt-later.** Traffic recorded today must stay
|
||||
secret after a cryptographically relevant quantum computer exists. This needs a
|
||||
post-quantum key exchange now.
|
||||
2. **Post-quantum authentication, later.** Needs certificates whose CA signature and host
|
||||
keys are post-quantum. This requires reissuing certificates, so it ships second.
|
||||
2. **Post-quantum authentication.** Needs certificates whose CA signature and host keys are
|
||||
post-quantum, so certificates have to be reissued or extended. Post-quantum key exchange
|
||||
ships only together with it: there is no post-quantum handshake on version 2 certificates.
|
||||
3. **Never rely on IP fragmentation.** ML-KEM and ML-DSA do not fit in one packet, so the
|
||||
handshake must carry messages larger than the path MTU itself.
|
||||
|
||||
@@ -25,78 +27,211 @@ The only signature in the system stays the CA signature inside the certificate.
|
||||
| ML-DSA-87 public key / signature | 2592 B / 4627 B |
|
||||
| Today's IX msg1 / msg2 (v2 cert, 151 B) | 252 B / 287 B |
|
||||
|
||||
`crypto/mlkem` is available in Go 1.26 (the current `go.mod`); `crypto/mldsa` arrives in
|
||||
Go 1.27 and is only needed for phase 2.
|
||||
`crypto/mlkem` is available in Go 1.26; `crypto/mldsa` arrives in Go 1.27, which `go.mod`
|
||||
requires.
|
||||
|
||||
## Phase 1: ephemeral ML-KEM on today's certificates
|
||||
## An ephemeral-KEM handshake, built and dropped
|
||||
|
||||
A new handshake subtype, `ix_psk2_mlkem1024` (2), IX-shaped (2 messages; the responder
|
||||
completes on msg1 as today), using the flynn/noise `psk2` modifier. The Noise protocol name
|
||||
becomes `Noise_IXpsk2_...`, which separates it from the classical subtype.
|
||||
The first design was `ix_psk2_mlkem1024`: classical IX on version 2 certificates with an ephemeral
|
||||
ML-KEM-1024 exchange mixed in through the `psk2` slot, so recorded traffic was protected without
|
||||
reissuing certificates. It was built, field tested and then dropped on 2026-10-14, before any
|
||||
release. Post-quantum handshakes ship hybrid only, for three reasons:
|
||||
|
||||
- **msg1**: the initiator generates a fresh ML-KEM-1024 key pair and places the
|
||||
encapsulation key in `NebulaHandshakeDetails.KEMKey` (field 9). msg1's payload is mixed
|
||||
into the Noise transcript, so it cannot be stripped or replaced without msg2 failing.
|
||||
With the psk modifier Noise also mixes `e` into the cipher key, so msg1's static key and
|
||||
payload are encrypted, though only under a key derived from the public ephemeral.
|
||||
- **Responder**: after `ReadMessage(msg1)` it encapsulates to that key, obtaining
|
||||
`(ct, ss)`, and calls `HandshakeState.SetPresharedKey(psk)` before writing msg2, with
|
||||
`psk = HKDF-Extract(SHA-256, salt = "nebula ix_psk2_mlkem1024 v1", ikm = ss || ct)`.
|
||||
The ciphertext is bound in because, unlike the encapsulation key, it is not part of the
|
||||
Noise transcript.
|
||||
- **msg2** on the wire is `ct || noise_msg2`. The ciphertext travels outside the Noise
|
||||
message because the initiator needs `ss` before processing msg2's `psk` token. Any change
|
||||
to `ct` yields a different `ss` (ML-KEM implicit rejection) and the handshake fails.
|
||||
- It left authentication classical, which a deployment wanting quantum safety needs anyway, and
|
||||
a second post-quantum handshake would be twice the code to review and keep.
|
||||
- It completes in two messages, so the responder could not tell which of two crossing attempts
|
||||
the initiator kept (see [Crossing attempts](#three-messages-in-the-manager)); on real hosts 5 of
|
||||
100 first pings failed at 50 ms round trip for that reason.
|
||||
- Its `psk` token came last in msg2, so the responder's static key travelled under classical keys
|
||||
only.
|
||||
|
||||
Transport keys depend on both the X25519 DH outputs and the ML-KEM shared secret.
|
||||
Authentication is unchanged and classical. With a minimal v2 certificate msg1 and msg2 are
|
||||
about 1.84 KB each, so each travels as 2 data and 2 repair fragments of about 936 bytes.
|
||||
A KEM key on the classical subtype, or a missing or malformed one on this subtype, is a fatal
|
||||
protocol error; a forged ciphertext only fails that packet.
|
||||
Subtype 2 and payload field 9 (its encapsulation key) stay reserved. The code is on the
|
||||
`pq-handshake` branch for reference.
|
||||
|
||||
## Phase 2: pqIX hybrid with certificate v3
|
||||
## Hybrid IX with certificate v3
|
||||
|
||||
Certificate v3 is hybrid: the classical static key and CA signature plus a static
|
||||
ML-KEM-1024 key and an ML-DSA-87 CA signature. Host authentication is by KEM rather than by
|
||||
signature, following PQNoise's pqIX, while keeping the classical DH tokens:
|
||||
Decided on 2026-10-14 and implemented on the `pq-identity` branch (see
|
||||
[Implementation](#implementation-certificates-and-the-hybrid-handshake)).
|
||||
|
||||
- **msg1** (I to R): `e, s`, ephemeral ML-KEM key, initiator cert.
|
||||
- **msg2** (R to I): `e, s`, ciphertext to I's ephemeral KEM key, ciphertext to I's static
|
||||
KEM key, responder cert.
|
||||
- **msg3** (I to R): ciphertext to R's static KEM key, plus first data. R authenticates I
|
||||
when msg3 decrypts; I authenticates R implicitly when R's first reply decrypts.
|
||||
### Certificate v3
|
||||
|
||||
msg3 is about 1.6 KB, 2 data and 2 repair fragments, and adds no new message types:
|
||||
A version 3 certificate is a version 2 certificate extended with post-quantum keys. It is its own
|
||||
format, with its own PEM banner (`NEBULA CERTIFICATE V3`) and a strict parser, but its first
|
||||
fields are exactly the fields of a v2 certificate:
|
||||
|
||||
- **Responder.** After sending msg2 the responder keeps a pending Machine, found by its
|
||||
local index like the initiator's today; this is the multi-message responder support the
|
||||
manager lacks now. A repeat msg1 maps to it through the answered-msg1 cache and gets msg2
|
||||
resent with fresh symbols, exactly as in phase 1. Until msg3 verifies, data for that
|
||||
index is dropped silently: it must not draw a RecvError, which would tear down the
|
||||
initiator's new tunnel. On completing it sends an empty `Test`/`TestReply` under the
|
||||
new keys, so the initiator hears back even when there is no traffic.
|
||||
- **Initiator.** Writing msg3 yields the transport keys, so the hostinfo moves to the main
|
||||
hostmap and data flows at once, readable only by the real responder. The handshake entry
|
||||
stays behind in a confirming state: each retry tick resends msg3 with fresh symbols until
|
||||
any packet from the responder decrypts on the new tunnel, and if that never happens
|
||||
within the handshake timeout the tunnel is torn down. Losing msg3 costs the data sent
|
||||
behind it, which the overlay's own transport retransmits.
|
||||
- msg3's fragments use the responder's index as RemoteIndex and land on the responder's
|
||||
pending entry, so they never enter the pre-authentication table.
|
||||
```
|
||||
CertificateV3 ::= SEQUENCE {
|
||||
details [0] Details, -- v2 details, unchanged
|
||||
curve [1] Curve DEFAULT curve25519,
|
||||
publicKey [2] OCTET STRING, -- classical: X25519 / P256 for hosts, Ed25519 / ECDSA P256 for CAs
|
||||
signature [3] OCTET STRING, -- classical CA signature over details || curve || publicKey, as in v2
|
||||
pqSuite [4] OCTET STRING, -- one byte, the PQSuite; always present
|
||||
pqPublicKey [5] OCTET STRING, -- the suite's KEM public key for hosts, its signature public key for CAs
|
||||
pqSignature [6] OCTET STRING -- the suite's signature by the issuing CA, context "nebula certificate v3",
|
||||
-- over the DER of fields 0 to 5, curve always present
|
||||
}
|
||||
```
|
||||
|
||||
The initiator never caches the responder's certificate, so every handshake has three
|
||||
messages and carries both full certificates. With ML-DSA-87:
|
||||
- **The suite.** `pqSuite` names the post-quantum algorithms the way `curve` names the classical
|
||||
ones: the KEM of host keys, and the signature algorithm of CA keys and of the certificates a CA
|
||||
signs. A CA and every certificate it signs share a suite, as they share a curve; the CA pool
|
||||
rejects a mismatch, and the post-quantum signature covers the suite, so a certificate can not be
|
||||
relabelled. The field is always present, in handshakes too, with no default, and 0 is never
|
||||
valid. There is one suite today, `MLKEM1024_MLDSA87` (1): ML-KEM-1024 hosts, ML-DSA-87 CAs. A
|
||||
new suite is an entry in the cert package's suite table plus, for a new KEM, a hybrid subtype; no
|
||||
new certificate version. Changing a CA's suite means a new CA, or a new v3 extension of its v2
|
||||
form that replaces the old one, since one v2 CA has one v3 extension.
|
||||
|
||||
| Message | Size | Data fragments (k) |
|
||||
- **The v2 form.** Fields 0 to 3 are a byte exact v2 certificate, signed by the v2 form of the CA.
|
||||
A v3 holder presents it in classical handshakes, so peers that only speak v2 accept
|
||||
it as they always have, and old parsers never see v3 bytes. A node therefore needs one
|
||||
certificate, not a v2 and v3 pair.
|
||||
- **Signatures.** Both must verify. The ML-DSA-87 signature covers the classical signature too, so
|
||||
neither signature can be swapped out (which also makes P256 low/high-s alternates moot for v3).
|
||||
If ML-DSA fell classically and someone swapped `pqPublicKey`, the hybrid handshake still needs
|
||||
the classical static key, which only the classical signature covers. The ML-DSA-87 signature is
|
||||
deterministic (FIPS 204 section 3.4), so extending the same v2 certificate with the same key twice
|
||||
gives the same v3 certificate and fingerprint: `pq-extend` is idempotent. The hedged variant
|
||||
guards signers an attacker can fault physically, which a CA key in a file is not, and the Ed25519
|
||||
signature beside it is deterministic too.
|
||||
- **Issuer and fingerprints.** The details are v2-shaped, so the issuer is the fingerprint of the
|
||||
CA's v2 form. A v3 certificate's own fingerprint is the SHA-256 of its whole encoding and differs
|
||||
from its v2 form's. Both identify it. To block a v3 certificate, block its v2 fingerprint: the
|
||||
pool checks it for the v3 certificate and for its v2 form alike, so one entry covers both forms,
|
||||
while blocking only the v3 fingerprint leaves the v2 form usable in classical handshakes.
|
||||
`nebula-cert print` leads with both fingerprints and says which one to block. Firewall `ca_sha`
|
||||
rules match a v3 peer by either fingerprint of its CA.
|
||||
- **CA pool.** A v3 CA verifies only v3 certificates. To accept v2 certificates as well the pool
|
||||
must also list the CA's v2 form. Dropping the v2 form is how a node requires post-quantum
|
||||
authentication; there is no separate setting. Two different v3 extensions of one v2 CA are
|
||||
rejected as ambiguous.
|
||||
- **Keys are composite**, classical followed by post-quantum, wherever a v3 certificate deals in
|
||||
them: `PublicKey()` returns `classical || pq`, and private keys are `classical || seed` (64 byte
|
||||
ML-KEM seed for hosts, 32 byte ML-DSA seed for CAs), in one PEM block in `pki.key` with banners
|
||||
such as `NEBULA X25519 MLKEM1024 PRIVATE KEY` and `NEBULA ED25519 MLDSA87 PRIVATE KEY`. The
|
||||
banner names the post-quantum algorithm, not the suite, because a seed's size does not tell the
|
||||
algorithm's strength.
|
||||
- **Both curves.** Curve25519 and P256; the post-quantum half does not depend on the curve.
|
||||
- **In-place upgrade.** `nebula-cert pq-extend` turns an existing v2 CA into a v3 CA whose v2 form
|
||||
is the old CA certificate, byte for byte, and extends existing host certificates the same way.
|
||||
Fingerprints, blocklists and trust in the v2 forms carry over unchanged. Hosts get their ML-KEM
|
||||
key with `nebula-cert keygen -in-key`, which keeps the classical key.
|
||||
|
||||
| Certificate | Full | In a handshake | v2 form |
|
||||
|---|---|---|---|
|
||||
| CA, Curve25519 | 7365 B | n/a | 134 B |
|
||||
| Host, Curve25519 | 6378 B | 4772 B | 171 B |
|
||||
|
||||
`crypto/mldsa` is new in Go 1.27, so `go.mod` moves to Go 1.27.
|
||||
|
||||
### Handshake
|
||||
|
||||
A new subtype, `ix_hybrid_mlkem1024` (3), runs `HandshakeHybridIX` from
|
||||
[github.com/DefinedNet/noise](https://github.com/DefinedNet/noise) (its `PQ_RESEARCH.md` gives the
|
||||
design rationale and security argument), with ML-KEM-1024 supplied by nebula:
|
||||
|
||||
```
|
||||
-> e, s
|
||||
<- ekem, skem, e, ee, se, s, es
|
||||
-> skem
|
||||
```
|
||||
|
||||
- `e` and `s` carry composite keys, X25519 (or P256) followed by ML-KEM-1024. DH tokens use the
|
||||
classical halves, `ekem` and `skem` encapsulate to the ML-KEM halves, and every secret goes into
|
||||
the one chaining key.
|
||||
- **The responder's `e` is classical only.** It follows the responder's `ekem`, which already
|
||||
completed the ephemeral KEM exchange, so it carries only the X25519 (or P256) key that `ee` and
|
||||
`se` need. A second ephemeral KEM exchange would add nothing: one `ekem` is lost only if the
|
||||
initiator's ephemeral private key or the responder's encapsulation randomness is, and a reverse
|
||||
one would be lost in the same cases. PQNoise's pqIX has no responder `e` at all. The static ML-KEM key is the post-quantum half of the certificate's public
|
||||
key, so it travels in `s` and the handshake form of the certificate leaves out both keys.
|
||||
- **KEM tokens first.** msg2 starts with `ekem, skem`, so the responder's static key and
|
||||
certificate are encrypted under keys that already include both KEM secrets: the responder's
|
||||
identity is protected against harvest-now-decrypt-later, as TLS 1.3 with `X25519MLKEM768`
|
||||
protects the server certificate. (OpenSSH offers no comparison: its hybrid key exchange sends the
|
||||
host key in the clear.) The initiator's certificate travels in msg1 in the clear, as in IX today.
|
||||
- **Authentication.** The responder authenticates the initiator when msg3 decrypts (it depends on
|
||||
msg2's `skem` to the initiator's static key); the initiator authenticates the responder when the
|
||||
first packet under the new keys decrypts (it depends on msg3's `skem`). Neither side needs a
|
||||
signature. Knowing only a peer's classical private key gets an impersonator nowhere: as an
|
||||
initiator it cannot read msg2, as a responder it cannot read msg3.
|
||||
- **The two static ML-KEM keys see different ciphertexts.** msg2's `skem` ciphertext is encrypted
|
||||
under a key derived from the `ekem` secret, which whoever sent msg2 chose, so anyone who can
|
||||
address a pending initiator's index can have the initiator decapsulate a ciphertext of their
|
||||
choosing with its static key. That is the IND-CCA setting ML-KEM is designed for, and
|
||||
`crypto/mlkem` is constant time. The responder decrypts msg3's `skem` ciphertext under the keys of
|
||||
a completed msg2 before decapsulating, so it only ever decapsulates ciphertexts the genuine
|
||||
initiator sealed.
|
||||
- v3 certificates go with this subtype and nothing else: a v3 certificate on any other subtype, or
|
||||
a v2 one on this one, is a protocol error.
|
||||
- **One subtype per KEM.** A hybrid subtype names its KEM, and a v3 holder initiates the subtype of
|
||||
its suite's KEM. Peers need the same KEM, not the same suite: suites that differ only in their
|
||||
signature algorithm share a subtype, and each certificate carries its own suite. A responder
|
||||
whose suite uses another KEM drops msg1, so the pair behaves as if the responder did not speak
|
||||
PQ: classical fallback, or no tunnel under `require`. A suite's KEM must have a subtype for the
|
||||
pki to load a certificate in it.
|
||||
|
||||
| Message | Size (Curve25519) | Data fragments (k) |
|
||||
|---|---|---|
|
||||
| msg1 | ~8.2 KB | 8 |
|
||||
| msg2 | ~9.8 KB | 9 |
|
||||
| msg3 | ~1.6 KB | 2 |
|
||||
| msg1 | 8009 B | 7 |
|
||||
| msg2 | 9628 B | 9 |
|
||||
| msg3 | 1616 B | 2 |
|
||||
|
||||
flynn/noise cannot mix multiple KEM secrets into the chaining key, so phase 2 needs a
|
||||
KEM-aware Noise symmetric state written in this repository. Both subtypes coexist.
|
||||
**Dependency.** DefinedNet/noise is a private repository today. `go.mod` points at a local clone
|
||||
with a `replace` directive; the module has to be published (or the hybrid patterns upstreamed to
|
||||
flynn/noise) before this can merge.
|
||||
|
||||
Cryptographic review of the hybrid composition will be done by in-house cryptographers.
|
||||
### Three messages in the manager
|
||||
|
||||
- **Responder.** After msg2 the responder keeps the handshake pending under its local index, the
|
||||
multi-message responder the manager lacked before. A repeated msg1 maps to it through the
|
||||
answered-msg1 cache and gets msg2 resent with fresh symbols. msg3's fragments name
|
||||
the responder's index, so they reach the pending entry and never the pre-authentication table;
|
||||
its reassembly is capped at 4 KiB. Until msg3 verifies, data for that index is dropped quietly:
|
||||
a RecvError would tear down the initiator's new tunnel. On completing, the responder sends an
|
||||
empty `Test`/`TestReply` under the new keys so the initiator hears back without traffic. A
|
||||
pending responder expires after the handshake timeout.
|
||||
- **Initiator.** Writing msg3 yields the transport keys, so the tunnel goes live at once, readable
|
||||
only by the real responder; msg3 goes out before any packets cached during the handshake. Until
|
||||
anything from the responder decrypts on the new tunnel, msg3 is resent with fresh symbols on a
|
||||
linear backoff, and if nothing has decrypted by the handshake timeout the tunnel is closed.
|
||||
Losing msg3 costs the data sent right behind it, which the overlay retransmits.
|
||||
- **Lost confirmation.** A msg3 fragment for a v3 tunnel the responder already completed means the
|
||||
initiator is still waiting, so the responder confirms again, at most once per retry interval and
|
||||
only to the tunnel's own remote, never to the fragment's source.
|
||||
- **Crossing attempts.** The initiator alternates, and its first classical attempt follows the
|
||||
hybrid msg1 anywhere from right away to three retry intervals later (the retry timer lands two
|
||||
slots ahead on the timer wheel, which moves on whole ticks), so at real round-trip times it
|
||||
often goes out before msg2 is back. Answered, it would complete at once on the responder while
|
||||
the hybrid handshake waits for msg3. So for four retry intervals after answering a peer's new
|
||||
hybrid msg1, the responder leaves that peer's classical msg1s unanswered: the crossing one
|
||||
arrives within the window whatever the round trip, because both take the same path. The
|
||||
window is short so an initiator whose hybrid attempt fails on its own side (one that does not
|
||||
yet trust our v3 CA, during a rollout) still gets a classical answer to a later attempt; a
|
||||
block lasting as long as the hybrid state would refuse it until its handshake timed out, and
|
||||
its next handshake would start with a hybrid msg1 again. A classical msg1 that still crosses,
|
||||
past the window on a very slow path, is answered, but msg3 settles it: the initiator only
|
||||
sends msg3 after committing to hybrid, so the responder takes the hybrid tunnel even though
|
||||
the classical one is newer, rather than rejecting it as too old.
|
||||
- **A failed attempt.** A post-quantum attempt can fail fatally where the classical one would not,
|
||||
for example a v3 certificate from a CA the initiator trusts only in its v2 form. The failed
|
||||
attempt is dropped and the handshake continues classical. With `require` the handshake ends.
|
||||
|
||||
### Rollout with v3
|
||||
|
||||
- `handshakes.pq` only does anything on a node with a v3 certificate. Without one, `initiate`,
|
||||
`accept` and `sticky` log a warning and are ignored, and `require` is refused at startup and
|
||||
on reload, since such a node could reach no one.
|
||||
- A responder without a v3 certificate, or whose suite uses another KEM, drops hybrid msg1s
|
||||
before reassembly, and the initiator falls back to classical.
|
||||
- `handshakes.pq.require` means hybrid only, in both directions, so every peer needs a v3
|
||||
certificate.
|
||||
- Post-quantum authentication is required through the CA pool, by not listing the CA's v2 form.
|
||||
A sticky or `require` initiator resists active downgrade of the key exchange; only the CA pool
|
||||
resists downgrade of authentication, since a quantum attacker could forge a v2 form.
|
||||
- `sticky` stays off by default for v3 holders too (decided 2026-10-14): a peer re-issued back to a
|
||||
v2-only certificate would otherwise be unreachable until this process restarts. Deployments that
|
||||
want downgrade resistance turn on `sticky` or `require`, or drop the CA's v2 form from the pool.
|
||||
|
||||
## Fragment transport
|
||||
|
||||
@@ -186,9 +321,15 @@ Implemented in `handshake/fragment` (`Sender`, `Assembly`, and the capped `Table
|
||||
however many repair symbols arrive.
|
||||
- When K symbols are present the message is decoded and handed to the handshake `Machine`
|
||||
as a synthetic `[header | message]`. The Machine never sees fragments.
|
||||
- A completed entry is forgotten immediately. A late duplicate fragment starts a new entry
|
||||
and, once enough arrive, reconstructs the same message again; the handshake layer's
|
||||
duplicate detection recognises it.
|
||||
- A completed message the responder answered is remembered without its symbols, outside the
|
||||
memory and per-source caps, for the idle timeout: which symbol indexes it has seen, and its
|
||||
hash. Fragments still trailing the attempt that completed it are counted and dropped. Once as
|
||||
many new symbols as it has data symbols arrive, which only a retry offers, it is reported as a
|
||||
repeat and the cached response is resent. Without this, the repair fragments trailing a msg1
|
||||
whose data fragments already completed it open an entry that for K above the repair count can
|
||||
never complete, and back to back handshakes from one source run into its quota (seen on real
|
||||
hosts: the fifth hybrid handshake within 3 s fell back to classical). A message that decoded
|
||||
but was not answered is forgotten, and the next attempt rebuilds it.
|
||||
- If Noise rejects a decoded message, the entry is discarded and the next attempt
|
||||
supplies fresh symbols. (Possible refinement: keep a few spare symbols so an injected
|
||||
bad symbol can be identified by re-encoding instead of waiting for a retry.)
|
||||
@@ -196,18 +337,37 @@ Implemented in `handshake/fragment` (`Sender`, `Assembly`, and the capped `Table
|
||||
FragID) with a total memory cap, per-source quotas (/32 for IPv4, /64 for IPv6), a
|
||||
sliding TTL of about 2 s refreshed by progress, and random eviction under pressure.
|
||||
msg2 and msg3 reassembly attaches to the existing pending handshake found by RemoteIndex.
|
||||
The initiator keeps two msg2 slots keyed by the responder's FragID, each capped at 16 KiB.
|
||||
When a stale lighthouse address for the peer belongs to another host now, both hosts answer
|
||||
the same msg1, and their interleaved bursts would wipe each other out of a single slot that
|
||||
emptied on every FragID change; with a slot each, whichever completes first is processed, and
|
||||
a wrong host's answer takes the usual block-and-retry path. The responder's msg3 slot needs no
|
||||
such care: it checks FragID against the initiator's index it learned from msg2.
|
||||
|
||||
### Retransmission and amplification
|
||||
|
||||
- Only timers cause transmission. Reactive resends (the responder resending its cached
|
||||
msg2 when a duplicate msg1 completes) are rate limited to one per handshake per retry
|
||||
interval, to avoid TFTP's Sorcerer's Apprentice amplification.
|
||||
- Only timers cause transmission, with one reactive exception: the responder resends its
|
||||
cached msg2 when a copy of msg1 completes again. An initiator sends msg1 to every address
|
||||
it knows and through its relays, the responder reassembles each path separately, and each
|
||||
path's first completion is answered on that path at once. A path that only works one way,
|
||||
say a responder answering from the wrong interface, is then covered by the others in the
|
||||
same attempt, and the initiator keeps the union of the msg2 symbols that reach it. After
|
||||
that a path is answered again at most once per retry interval, and only once K symbols not
|
||||
seen before on it arrive: duplicates do nothing, and there are 256 symbols per message, so
|
||||
a resend costs the initiator K packets on that path and the answer is held to the 3x
|
||||
budget below. That is TFTP's Sorcerer's Apprentice bound, per path rather than per
|
||||
handshake.
|
||||
A path is only an address and port, so a recently answered msg1 replayed from spoofed
|
||||
sources draws one cached msg2 to each, at about 1.2-1.4x the bytes sent and never over 3x,
|
||||
for as long as the answered msg1 is remembered (the handshake timeout). Accepted
|
||||
(2026-10-15): classical IX already resends its stored msg2 to any source that replays msg1,
|
||||
with no clock at all, and a per-handshake clock is what broke a path that only works one way.
|
||||
- Duplicate msg1 detection compares the decoded message to the cached one **before**
|
||||
running Noise or certificate verification.
|
||||
- Before an address is validated, a responder sends at most 3x the bytes it received from
|
||||
it (QUIC's rule). Normal handshakes sit near 1.1-1.2x.
|
||||
- In phase 2 the initiator retransmits msg3 until any authenticated packet arrives from
|
||||
the responder; the responder sends a small confirmation on completion and holds tunnel
|
||||
- The initiator retransmits msg3 until any authenticated packet arrives from
|
||||
the responder; the responder sends a small confirmation on completion and drops tunnel
|
||||
traffic until msg3 verifies.
|
||||
|
||||
### Denial of service
|
||||
@@ -235,6 +395,21 @@ WireGuard's mac2, QUIC Retry and the SCTP state cookie:
|
||||
|
||||
A CA-keyed pre-filter MAC was considered and rejected: networks commonly trust many CAs.
|
||||
|
||||
#### Pending hybrid responders
|
||||
|
||||
A hybrid responder that answered msg1 keeps a pending entry, keyed by its local index, until
|
||||
msg3 arrives or the handshake timeout (5.5 s by default) passes. msg1 is cleartext and nothing
|
||||
covers `e` or `Time`, so from one captured v3 msg1 an attacker can mint distinct valid msg1s
|
||||
with a fresh `e` and a bumped `Time`. Each misses the answered-msg1 cache, costs the responder
|
||||
the whole msg1 (two signature verifications, two encapsulations, four DH operations, the
|
||||
certificate checks) and a pending entry, and the fragment table stays near empty because a
|
||||
complete burst arrives together, so cookies are never demanded and spoofed sources work.
|
||||
Pending entries are not bounded per peer or in total. Accepted as is (2026-10-14): the per-msg1
|
||||
work is the same class as classical IX's pre-authentication cost, the expiry bounds the state in
|
||||
time and the fragment table bounds bytes in flight. If it needs tightening, cap pending
|
||||
responders per certificate fingerprint and in total, and count them toward the cookie
|
||||
threshold.
|
||||
|
||||
#### Injected symbols
|
||||
|
||||
The decoder keeps the first K distinct symbols it sees, so one forged symbol in those K
|
||||
@@ -256,7 +431,7 @@ does not downgrade.
|
||||
`handshakes.pq.initiate`, `handshakes.pq.accept`. `handshakes.pq.repair_delay` (default
|
||||
10ms) sets how long repair fragments trail the data fragments.
|
||||
- `handshakes.pq.require` makes every handshake PQ: it implies `initiate` and `accept`,
|
||||
never offers a classical attempt, and drops classical msg1s.
|
||||
never offers a classical attempt, and drops classical msg1s. It needs a v3 certificate.
|
||||
- Old nodes silently drop unknown subtypes, so discovery is speculative: an initiator with
|
||||
`initiate` enabled alternates PQ and classical attempts on successive timer retries,
|
||||
keeping both pending, and the first to complete wins. A path nothing has been sent over
|
||||
@@ -281,14 +456,14 @@ mean burst length in packets. First-attempt success for the whole handshake with
|
||||
|
||||
| Handshake | Loss | Burst 1 | Burst 2 | Burst 4 | Burst 8 |
|
||||
|---|---|---|---|---|---|
|
||||
| phase 1 (2, 2) no FEC | 5% | 81.4% | 85.6% | 87.9% | 89.0% |
|
||||
| phase 1 (2, 2) FEC | 5% | 99.9% | 99.4% | 99.3% | 98.6% |
|
||||
| phase 1 (2, 2) FEC | 10% | 99.3% | 97.5% | 97.4% | 96.3% |
|
||||
| phase 2 (7, 9, 2) no FEC | 5% | 39.8% | 57.5% | 70.4% | 77.7% |
|
||||
| phase 2 (7, 9, 2) FEC | 5% | 99.6% | 94.2% | 90.4% | 88.8% |
|
||||
| phase 2 (7, 9, 2) FEC | 10% | 95.9% | 84.6% | 79.0% | 77.3% |
|
||||
| two messages (2, 2) no FEC | 5% | 81.4% | 85.6% | 87.9% | 89.0% |
|
||||
| two messages (2, 2) FEC | 5% | 99.9% | 99.4% | 99.3% | 98.6% |
|
||||
| two messages (2, 2) FEC | 10% | 99.3% | 97.5% | 97.4% | 96.3% |
|
||||
| hybrid (7, 9, 2) no FEC | 5% | 39.8% | 57.5% | 70.4% | 77.7% |
|
||||
| hybrid (7, 9, 2) FEC | 5% | 99.6% | 94.2% | 90.4% | 88.8% |
|
||||
| hybrid (7, 9, 2) FEC | 10% | 95.9% | 84.6% | 79.0% | 77.3% |
|
||||
|
||||
With fresh repair symbols, phase 2 completes within two attempts at least 99.1% of the time
|
||||
With fresh repair symbols, the hybrid handshake completes within two attempts at least 99.1% of the time
|
||||
in every scenario above, and within three at least 99.99%.
|
||||
|
||||
## Prior art
|
||||
@@ -308,10 +483,8 @@ in every scenario above, and within three at least 99.99%.
|
||||
- **TFTP, NFS duplicate request cache, memcached UDP, IP reassembly bugs**: retransmit
|
||||
storms, ID-wrap misassembly, reflection amplification, and allocation from claimed sizes.
|
||||
|
||||
## Implementation (phase 1)
|
||||
## Implementation: fragment transport and manager
|
||||
|
||||
- `handshake`: the `ix_psk2_mlkem1024` subtype (`patterns.go`, `kem.go`), the `KEMKey`
|
||||
payload field, and the psk2 plumbing in `Machine`.
|
||||
- `handshake/fec`, `handshake/fragment`: the code and the fragment transport.
|
||||
- `handshake_manager_pq.go` and the manager:
|
||||
- **Initiator.** Attempts alternate PQ and classical, starting with PQ (sticky peers get
|
||||
@@ -323,22 +496,68 @@ in every scenario above, and within three at least 99.99%.
|
||||
certificate work: the trailing repair fragments of an attempt rebuild a msg1 its data
|
||||
fragments already completed, and a retrying initiator offers fresh symbols for the
|
||||
same msg1. A repeat goes straight to the cached-response resend, which offers fresh
|
||||
msg2 symbols, is rate limited to one per retry interval and is held to the 3x
|
||||
amplification budget.
|
||||
msg2 symbols on the path the repeat came by and is held to the 3x amplification
|
||||
budget.
|
||||
- **Relays** carry fragments unchanged; repair fragments trail via a timer.
|
||||
- The pre-authentication table is capped at 4 MiB, 1024 entries, 4 per source (IPv4 /32,
|
||||
IPv6 /64, or relay channel), 16 KiB messages and a 3 s idle timeout. Cookies are
|
||||
demanded from half full.
|
||||
- Tests: Noise-level KEM tests, codec and fragment tests and fuzzers, manager unit tests
|
||||
for the response budget and rate limit, and e2e tests for a clean handshake, loss of
|
||||
- Tests: codec and fragment tests and fuzzers, manager unit tests
|
||||
for the response budget, table tests for the per-path repeat clock, and e2e tests for a clean handshake, loss of
|
||||
data fragments in both directions, fallback to a peer that does not accept PQ, a lost
|
||||
msg2 recovered by fresh symbols, sticky mode under an attacker dropping PQ packets,
|
||||
relays, index cleanup on completion, fallback and timeout, and a responder flooded from
|
||||
relays, a direct msg2 lost on every attempt and answered through a relay instead, index
|
||||
cleanup on completion, fallback and timeout, and a responder flooded from
|
||||
spoofed sources demanding and accepting a cookie. Unit tests cover cookie binding and
|
||||
rotation, the never-amplify rule, the initiator's rate limited resend, and reload. ML-KEM and HKDF also
|
||||
pass under `GOEXPERIMENT=boringcrypto` and `GODEBUG=fips140=on`.
|
||||
rotation, the never-amplify rule, the initiator's rate limited resend, and reload. ML-KEM also
|
||||
passes under `GOEXPERIMENT=boringcrypto` and `GODEBUG=fips140=on`.
|
||||
|
||||
## Implementation: certificates and the hybrid handshake
|
||||
|
||||
- `cert`: `cert_v3.go` (format, `V2Form`, `ExtendToV3`, `SignPQ`), `pq_suite.go` (`PQSuite` and
|
||||
the suite table), `SignHybridWith` and the composite `Sign` path, the CA pool's v3 index, suite
|
||||
check and v2-form blocklisting, and the composite key PEM banners, generated per suite.
|
||||
- `handshake`: the `ix_hybrid_mlkem1024` subtype on `noise.HandshakeHybridIX`, `KEMMLKEM1024`,
|
||||
`HybridSubtype` mapping a suite to the subtype of its KEM,
|
||||
composite credentials, cipher states ordered by role for three message patterns, and
|
||||
`Machine.PeerCert` for a responder that has to act before completion.
|
||||
- `pki.go` loads a v3 certificate with its composite key and derives the v2 form; messages after
|
||||
the handshake treat v3 tunnels as v2 (`protocolVersion`).
|
||||
- `handshake_manager_hybrid.go`: pending responders, confirmation and reconfirmation, the
|
||||
initiator's msg3 resends and teardown, and the crossing window; `outside.go` keeps quiet about
|
||||
pending responder indexes.
|
||||
- `nebula-cert`: `ca`, `keygen` and `sign` take `-version 3`, `keygen -in-key` extends an existing
|
||||
host key, `sign -version 2` with a v3 CA signs as its v2 form, and `pq-extend` upgrades v2
|
||||
certificates in place, keeping an encrypted CA key encrypted. `ca`, `keygen` and `pq-extend` of a
|
||||
CA take `-pq-suite`; `sign` and `pq-extend` of a host take the CA's suite.
|
||||
- Tests: certificate format, strictness, tampering, pool and blocklist rules and in-place
|
||||
extension on both curves; Machine-level hybrid handshakes including corrupted msg3 and
|
||||
impersonation with only the classical key; e2e tests for a clean hybrid handshake, a lost
|
||||
confirmation, a never confirmed handshake (no RecvErrors, teardown, expiry), a v2-only peer, an
|
||||
initiator that trusts only the v2 form, `require` both ways, and relays; pki loading; firewall
|
||||
`ca_sha`; and the `nebula-cert` flows.
|
||||
|
||||
## Open items
|
||||
|
||||
None for phase 1. Phase 2 needs certificate v3, the KEM-aware Noise symmetric state, and
|
||||
the msg3 design above.
|
||||
- Publish DefinedNet/noise and drop the `replace` in `go.mod`, once Nate says the fork is ready to
|
||||
ship. The classical-only responder `e` is on the local clone's `drop-responder-ekem-key` branch
|
||||
(b4a892b), not yet in DefinedNet/noise.
|
||||
- DefinedNet/noise `ReadMessage` returns `ErrShortMessage` without rolling back the symmetric
|
||||
state ([DefinedNet/noise#2](https://github.com/DefinedNet/noise/issues/2), inherited from
|
||||
flynn/noise). A message that fails a length check after a key-mixing token leaves `ck` and `h`
|
||||
advanced, so the genuine message can never be read: one spoofed short packet to a pending
|
||||
initiator's index, which msg1 carries in the clear in every IX variant, kills that attempt until
|
||||
it times out, and the Machine reports it as recoverable. Blocks publishing the module; the fix is
|
||||
a deferred rollback that also restores `k`, `n` and `hasK`. Smaller pre-publish items are in
|
||||
[DefinedNet/noise#3](https://github.com/DefinedNet/noise/issues/3).
|
||||
Field tested on real hosts on 2026-10-14 (`pq-lab/2026-10-14-hybrid/`, untracked): LAN median 3.2 ms
|
||||
against 1.4 ms classical, +2.0 ms at 50 ms round trip, no fallbacks with `require` under loss.
|
||||
|
||||
The cryptographic review of 2026-10-14 found no break in the composition or the certificate
|
||||
chain. Its outcomes are folded in above: deterministic ML-DSA signing, the fingerprint guidance,
|
||||
the `skem` oracle note, the psk2 note (moot now that handshake is dropped), the pending-responder
|
||||
exposure and the `sticky` default.
|
||||
|
||||
Accepted as is: a tunnel that came up classical between two v3 holders (say, the hybrid attempt
|
||||
was dropped) stays classical until it rehandshakes for another reason. `require`, `sticky` and a
|
||||
CA pool without v2 forms cover deployments that need more. PKCS#11 keys do not support v3.
|
||||
+13
-93
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/e2e/router"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
@@ -79,7 +78,7 @@ func (ht *handshakeTally) observe(p *udp.Packet) {
|
||||
}
|
||||
ht.Lock()
|
||||
defer ht.Unlock()
|
||||
if h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
if h.Subtype == header.HandshakeIXHybridMLKEM1024 {
|
||||
ht.pq++
|
||||
ht.maxPQLen = max(ht.maxPQLen, len(p.Data))
|
||||
} else {
|
||||
@@ -102,11 +101,14 @@ func isTunnelData(p *udp.Packet, receiver, to *nebula.Control) bool {
|
||||
return h.Type == header.Message && h.Subtype == header.MessageNone
|
||||
}
|
||||
|
||||
// newPQPair builds two hosts with v3 certificates that also trust the CA's v2
|
||||
// form, so a classical handshake can complete when the hybrid one does not.
|
||||
func newPQPair(t *testing.T, mine, theirs m) (myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, myUdp, theirUdp netip.AddrPort, r *router.R) {
|
||||
t.Helper()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
myControl, myVpn, myUdp, _ = newSimpleServer(cert.Version2, ca, caKey, "me", "10.128.0.1/24", mine)
|
||||
theirControl, theirVpn, theirUdp, _ = newSimpleServer(cert.Version2, ca, caKey, "them", "10.128.0.2/24", theirs)
|
||||
ca := newHybridCA(t)
|
||||
ca2, _ := ca.v2()
|
||||
myControl, myVpn, myUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "me", "10.128.0.1/24", withCA(mine, ca.ca, ca2))
|
||||
theirControl, theirVpn, theirUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "them", "10.128.0.2/24", withCA(theirs, ca.ca, ca2))
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
r = router.NewR(t, myControl, theirControl)
|
||||
myControl.Start()
|
||||
@@ -114,36 +116,6 @@ func newPQPair(t *testing.T, mine, theirs m) (myControl, theirControl *nebula.Co
|
||||
return
|
||||
}
|
||||
|
||||
func TestPQHandshake(t *testing.T) {
|
||||
t.Parallel()
|
||||
// They only accept, which is all a PQ initiator needs.
|
||||
myControl, theirControl, myVpn, theirVpn, myUdp, theirUdp, r := newPQPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally handshakeTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Zero(t, tally.classical, "no classical handshake should be needed")
|
||||
assert.GreaterOrEqual(t, tally.pq, 4, "both messages travel as several fragments")
|
||||
assert.LessOrEqual(t, tally.maxPQLen, fragment.MaxPacketLen)
|
||||
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true), "no pending index may outlive the handshake")
|
||||
assert.Empty(t, theirControl.ListHostmapIndexes(true))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQHandshakeLoss drops data fragments of both messages; the repair
|
||||
// fragments must carry the handshake without a retry.
|
||||
func TestPQHandshakeLoss(t *testing.T) {
|
||||
@@ -223,12 +195,12 @@ func TestPQResendFreshSymbols(t *testing.T) {
|
||||
case h != nil && fh == nil:
|
||||
// Keep the classical fallback out of the way.
|
||||
return router.Drop
|
||||
case fh != nil && h.MessageCounter == 2 && fh.Index < 4:
|
||||
case fh != nil && h.MessageCounter == 2 && fh.Index < 12:
|
||||
firstMsg2++
|
||||
return router.Drop
|
||||
case fh != nil && h.MessageCounter == 2:
|
||||
freshMsg2++
|
||||
case fh != nil && h.MessageCounter == 1 && fh.Index >= 4:
|
||||
case fh != nil && h.MessageCounter == 1 && fh.Index >= 10:
|
||||
freshMsg1++
|
||||
}
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
@@ -238,7 +210,7 @@ func TestPQResendFreshSymbols(t *testing.T) {
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Equal(t, 4, firstMsg2, "the first msg2 is 2 data and 2 repair fragments")
|
||||
assert.Equal(t, 12, firstMsg2, "the first msg2 is 9 data and 3 repair fragments")
|
||||
assert.Positive(t, freshMsg1, "the retry offers fresh msg1 symbols")
|
||||
assert.Positive(t, freshMsg2, "the resend offers fresh msg2 symbols")
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
@@ -268,7 +240,7 @@ func TestPQSticky(t *testing.T) {
|
||||
myControl.ReHandshake(theirVpn[0].Addr())
|
||||
r.RouteForAllExitFuncOrTimeout(time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if h, _ := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
if h, _ := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXHybridMLKEM1024 {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
@@ -280,58 +252,6 @@ func TestPQSticky(t *testing.T) {
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
func TestPQRelays(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version1, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
useRelays := pqConfig(true, true, false)
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
amRelay := pqConfig(true, true, false)
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version1, ca, caKey, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpnIpNet, relayUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version1, ca, caKey, "them ", "10.128.0.2/24", useRelays)
|
||||
|
||||
myControl.InjectLightHouseAddr(relayVpnIpNet[0].Addr(), relayUdpAddr)
|
||||
myControl.InjectRelays(theirVpnIpNet[0].Addr(), []netip.Addr{relayVpnIpNet[0].Addr()})
|
||||
relayControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||
|
||||
r := router.NewR(t, myControl, relayControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
|
||||
myControl.Start()
|
||||
relayControl.Start()
|
||||
theirControl.Start()
|
||||
|
||||
var tally handshakeTally
|
||||
var relayedPQ, relayedClassical int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(10*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
outer := &header.H{}
|
||||
if outer.Parse(p.Data) == nil && outer.Type == header.Message && outer.Subtype == header.MessageRelay {
|
||||
if h, fh := handshakeOf(p); h != nil && fh != nil {
|
||||
relayedPQ++
|
||||
assert.LessOrEqual(t, len(p.Data), fragment.MaxPacketLen+32, "a relayed fragment fits the IPv6 minimum MTU")
|
||||
} else if h != nil {
|
||||
relayedClassical++
|
||||
}
|
||||
}
|
||||
if isTunnelData(p, receiver, theirControl) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), 80, 80)
|
||||
assert.Positive(t, relayedPQ, "the end to end handshake is PQ through the relay")
|
||||
assert.Zero(t, relayedClassical, "the relay coming up carries the PQ attempt, not the classical retry")
|
||||
r.RenderHostmaps("Final hostmaps", myControl, relayControl, theirControl)
|
||||
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestPQTimeoutReleasesIndexes lets a handshake with both a PQ and a classical
|
||||
// attempt pending time out, and checks neither index is left behind.
|
||||
func TestPQTimeoutReleasesIndexes(t *testing.T) {
|
||||
@@ -370,7 +290,7 @@ func TestPQCookieUnderLoad(t *testing.T) {
|
||||
t.Log("Flood them with the first fragment of msg1s nobody will finish")
|
||||
for i := range 512 {
|
||||
from := netip.AddrPortFrom(netip.AddrFrom4([4]byte{198, 18, byte(i >> 8), byte(i)}), 4242)
|
||||
s, err := fragment.NewSender(make([]byte, 2000), header.HandshakeIXPSK2MLKEM1024, 0, 1, uint32(i+1))
|
||||
s, err := fragment.NewSender(make([]byte, 2000), header.HandshakeIXHybridMLKEM1024, 0, 1, uint32(i+1))
|
||||
require.NoError(t, err)
|
||||
pkts, _, err := s.Attempt(0)
|
||||
require.NoError(t, err)
|
||||
@@ -382,7 +302,7 @@ func TestPQCookieUnderLoad(t *testing.T) {
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if h, fh := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXPSK2MLKEM1024 {
|
||||
if h, fh := handshakeOf(p); h != nil && h.Subtype == header.HandshakeIXHybridMLKEM1024 {
|
||||
switch {
|
||||
case h.MessageCounter == 0:
|
||||
cookieReplies++
|
||||
|
||||
@@ -0,0 +1,708 @@
|
||||
//go:build e2e_testing
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/e2e/router"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// hybridTally counts handshake packets by subtype and message.
|
||||
type hybridTally struct {
|
||||
sync.Mutex
|
||||
hybrid, classical int
|
||||
msg3 int
|
||||
maxLen int
|
||||
}
|
||||
|
||||
func (ht *hybridTally) observe(p *udp.Packet) {
|
||||
h, _ := handshakeOf(p)
|
||||
if h == nil {
|
||||
return
|
||||
}
|
||||
ht.Lock()
|
||||
defer ht.Unlock()
|
||||
switch h.Subtype {
|
||||
case header.HandshakeIXHybridMLKEM1024:
|
||||
ht.hybrid++
|
||||
ht.maxLen = max(ht.maxLen, len(p.Data))
|
||||
if h.MessageCounter == 3 {
|
||||
ht.msg3++
|
||||
}
|
||||
default:
|
||||
ht.classical++
|
||||
}
|
||||
}
|
||||
|
||||
func isType(p *udp.Packet, t header.MessageType) bool {
|
||||
h := &header.H{}
|
||||
return h.Parse(p.Data) == nil && h.Type == t
|
||||
}
|
||||
|
||||
type hybridCA struct {
|
||||
ca cert.Certificate
|
||||
key []byte
|
||||
}
|
||||
|
||||
func newHybridCA(t *testing.T) hybridCA {
|
||||
t.Helper()
|
||||
ca, _, key, _ := cert_test.NewTestCaCert(cert.Version3, cert.Curve_CURVE25519, time.Now(), time.Now().Add(10*time.Minute), nil, nil, []string{})
|
||||
return hybridCA{ca: ca, key: key}
|
||||
}
|
||||
|
||||
// v2 returns the v2 form of the CA and its classical key, what a node that only has v2 certificates gets.
|
||||
func (h hybridCA) v2() (cert.Certificate, []byte) {
|
||||
return cert.V2Form(h.ca), h.key[:len(h.key)-cert.MLDSA87PrivateKeySize]
|
||||
}
|
||||
|
||||
// trust returns a pki.ca override trusting the given CAs.
|
||||
func trust(cas ...cert.Certificate) string {
|
||||
var s string
|
||||
for _, c := range cas {
|
||||
b, err := c.MarshalPEM()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
s += string(b)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func withCA(cfg m, cas ...cert.Certificate) m {
|
||||
if cfg == nil {
|
||||
cfg = m{}
|
||||
}
|
||||
cfg["pki"] = m{"ca": trust(cas...)}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func newHybridPair(t *testing.T, mine, theirs m) (myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, myUdp, theirUdp netip.AddrPort, r *router.R) {
|
||||
t.Helper()
|
||||
return newHybridPairWithCA(t, newHybridCA(t), mine, theirs)
|
||||
}
|
||||
|
||||
func newHybridPairWithCA(t *testing.T, ca hybridCA, mine, theirs m) (myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, myUdp, theirUdp netip.AddrPort, r *router.R) {
|
||||
t.Helper()
|
||||
myControl, myVpn, myUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "me", "10.128.0.1/24", mine)
|
||||
theirControl, theirVpn, theirUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "them", "10.128.0.2/24", theirs)
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
r = router.NewR(t, myControl, theirControl)
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
return
|
||||
}
|
||||
|
||||
func routeUntilData(t *testing.T, r *router.R, to *nebula.Control, timeout time.Duration, fn func(p *udp.Packet, receiver *nebula.Control) router.ExitType) bool {
|
||||
t.Helper()
|
||||
return r.RouteForAllExitFuncOrTimeout(timeout, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if fn != nil {
|
||||
if e := fn(p, receiver); e != router.KeepRouting {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if isTunnelData(p, receiver, to) {
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
}
|
||||
|
||||
func TestHybridHandshake(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, myUdp, theirUdp, r := newHybridPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally hybridTally
|
||||
var recvErrors int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if isType(p, header.RecvError) {
|
||||
recvErrors++
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Zero(t, tally.classical, "a node with a v3 certificate speaks the hybrid handshake")
|
||||
assert.GreaterOrEqual(t, tally.hybrid, 7+9+2, "all three messages travel as several fragments")
|
||||
assert.Positive(t, tally.msg3)
|
||||
assert.LessOrEqual(t, tally.maxLen, fragment.MaxPacketLen)
|
||||
assert.Zero(t, recvErrors)
|
||||
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
for _, c := range []*nebula.Control{myControl, theirControl} {
|
||||
assert.Empty(t, c.ListHostmapIndexes(true), "no pending index may outlive the handshake")
|
||||
}
|
||||
assert.Equal(t, cert.Version3, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false).Cert.Version())
|
||||
assert.Equal(t, cert.Version3, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false).Cert.Version())
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridConfirmationLost loses the responder's confirmation. The initiator
|
||||
// keeps resending msg3, and the responder, already done, confirms again rather
|
||||
// than leave the initiator to tear the tunnel down.
|
||||
func TestHybridConfirmationLost(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Three retries make the handshake timeout 400ms, so the wait below outlasts it.
|
||||
mine := pqConfig(true, true, false)
|
||||
mine["handshakes"].(m)["retries"] = 3
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newHybridPair(t, mine, pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally hybridTally
|
||||
var droppedConfirms, confirms int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
r.RouteForAllExitFuncOrTimeout(2*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if receiver == myControl && isType(p, header.Test) {
|
||||
if droppedConfirms == 0 {
|
||||
droppedConfirms++
|
||||
return router.Drop
|
||||
}
|
||||
confirms++
|
||||
return router.RouteAndExit
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
|
||||
assert.Equal(t, 1, droppedConfirms)
|
||||
assert.Positive(t, confirms, "the responder confirms again")
|
||||
assert.Greater(t, tally.msg3, 4, "msg3 was resent with fresh symbols")
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
|
||||
// Long past the handshake timeout, the tunnel must still be there.
|
||||
time.Sleep(700 * time.Millisecond)
|
||||
r.FlushAll()
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridNeverConfirmed loses every msg3. The responder never completes, must
|
||||
// not answer the initiator's data with RecvErrors meanwhile, and the initiator
|
||||
// closes the tunnel at the handshake timeout.
|
||||
func TestHybridNeverConfirmed(t *testing.T) {
|
||||
t.Parallel()
|
||||
mine := pqConfig(true, true, false)
|
||||
mine["handshakes"].(m)["retries"] = 3
|
||||
theirs := pqConfig(false, true, false)
|
||||
theirs["handshakes"].(m)["retries"] = 3
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newHybridPair(t, mine, theirs)
|
||||
defer r.RenderFlow()
|
||||
|
||||
var recvErrors, dropped int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
r.RouteForAllExitFuncOrTimeout(1500*time.Millisecond, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if h, fh := handshakeOf(p); fh != nil && h.MessageCounter == 3 {
|
||||
dropped++
|
||||
return router.Drop
|
||||
}
|
||||
if isType(p, header.RecvError) {
|
||||
recvErrors++
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
|
||||
assert.Greater(t, dropped, 4, "msg3 is resent")
|
||||
assert.Zero(t, recvErrors, "data for a pending responder is dropped quietly")
|
||||
assert.Nil(t, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false), "the responder never completes")
|
||||
assert.Nil(t, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false), "the initiator gave up on the tunnel")
|
||||
assert.Empty(t, theirControl.ListHostmapIndexes(true), "the pending responder expired")
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridToV2Peer has a v3 initiator meet a peer that holds only a v2
|
||||
// certificate. Its post-quantum settings do nothing without a v3 certificate, so
|
||||
// the tunnel comes up classical on the v2 form.
|
||||
func TestHybridToV2Peer(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
ca2, key2 := ca.v2()
|
||||
myControl, myVpn, myUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "me", "10.128.0.1/24", withCA(pqConfig(true, true, false), ca.ca, ca2))
|
||||
theirControl, theirVpn, theirUdp, _ := newSimpleServer(cert.Version2, ca2, key2, "them", "10.128.0.2/24", pqConfig(true, true, false))
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
r := router.NewR(t, myControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
|
||||
var tally hybridTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Positive(t, tally.hybrid, "the hybrid attempt comes first")
|
||||
assert.Positive(t, tally.classical)
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assert.Equal(t, cert.Version2, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false).Cert.Version())
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true))
|
||||
assert.Empty(t, theirControl.ListHostmapIndexes(true))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridDistrustedV3 has an initiator that trusts only the v2 form of the CA.
|
||||
// Its hybrid attempt fails verifying the responder's v3 certificate, which must
|
||||
// leave the classical attempt going rather than end the handshake.
|
||||
func TestHybridDistrustedV3(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
ca2, _ := ca.v2()
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newHybridPairWithCA(t, ca,
|
||||
withCA(pqConfig(true, true, false), ca2),
|
||||
withCA(pqConfig(false, true, false), ca.ca, ca2),
|
||||
)
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally hybridTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Positive(t, tally.hybrid)
|
||||
assert.Positive(t, tally.classical)
|
||||
assert.Equal(t, cert.Version2, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false).Cert.Version())
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true))
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridRequire checks require with a v3 certificate means hybrid only.
|
||||
func TestHybridRequire(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("both", func(t *testing.T) {
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newHybridPair(t, pqRequire(), pqRequire())
|
||||
defer r.RenderFlow()
|
||||
|
||||
var tally hybridTally
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.Zero(t, tally.classical)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
}
|
||||
|
||||
func TestHybridRelays(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
useRelays := pqConfig(true, true, false)
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
amRelay := pqConfig(true, true, false)
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
myControl, myVpnIpNet, _, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpnIpNet, relayUdpAddr, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpnIpNet, theirUdpAddr, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "them ", "10.128.0.2/24", useRelays)
|
||||
|
||||
myControl.InjectLightHouseAddr(relayVpnIpNet[0].Addr(), relayUdpAddr)
|
||||
myControl.InjectRelays(theirVpnIpNet[0].Addr(), []netip.Addr{relayVpnIpNet[0].Addr()})
|
||||
relayControl.InjectLightHouseAddr(theirVpnIpNet[0].Addr(), theirUdpAddr)
|
||||
|
||||
r := router.NewR(t, myControl, relayControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
|
||||
myControl.Start()
|
||||
relayControl.Start()
|
||||
theirControl.Start()
|
||||
|
||||
var relayedMsg3, relayedClassical int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpnIpNet[0].Addr(), 80, myVpnIpNet[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 10*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
outer := &header.H{}
|
||||
if outer.Parse(p.Data) == nil && outer.Type == header.Message && outer.Subtype == header.MessageRelay {
|
||||
if h, fh := handshakeOf(p); h != nil && fh != nil {
|
||||
assert.LessOrEqual(t, len(p.Data), fragment.MaxPacketLen+32, "a relayed fragment fits the IPv6 minimum MTU")
|
||||
if h.MessageCounter == 3 {
|
||||
relayedMsg3++
|
||||
}
|
||||
} else if h != nil {
|
||||
relayedClassical++
|
||||
}
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpnIpNet[0].Addr(), theirVpnIpNet[0].Addr(), 80, 80)
|
||||
assert.Positive(t, relayedMsg3, "msg3 goes through the relay too")
|
||||
assert.Zero(t, relayedClassical)
|
||||
r.RenderHostmaps("Final hostmaps", myControl, relayControl, theirControl)
|
||||
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridBackToBack rebuilds the tunnel more times than the responder's
|
||||
// per-source quota allows messages in progress, faster than its table expires
|
||||
// entries. The repair fragments trailing each completed msg1 must not count
|
||||
// against that quota, or later handshakes fall back to classical.
|
||||
func TestHybridBackToBack(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, _, theirUdp, r := newHybridPair(t, pqConfig(true, true, false), pqConfig(false, true, false))
|
||||
defer r.RenderFlow()
|
||||
|
||||
for i := range 6 {
|
||||
// Closing the last tunnel forgets the peer's address.
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, nil), "tunnel %d never came up", i)
|
||||
theirControl.GetFromTun(true)
|
||||
// Let the trailing repair fragments land before tearing down.
|
||||
r.RouteForAllExitFuncOrTimeout(50*time.Millisecond, func(*udp.Packet, *nebula.Control) router.ExitType { return router.KeepRouting })
|
||||
|
||||
mine := myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false)
|
||||
theirs := theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false)
|
||||
require.NotNil(t, mine)
|
||||
require.NotNil(t, theirs)
|
||||
assert.Equal(t, cert.Version3, mine.Cert.Version(), "tunnel %d is hybrid", i)
|
||||
assert.Equal(t, cert.Version3, theirs.Cert.Version(), "tunnel %d is hybrid", i)
|
||||
|
||||
myControl.CloseTunnel(theirVpn[0].Addr(), true)
|
||||
theirControl.CloseTunnel(myVpn[0].Addr(), true)
|
||||
}
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridRaceWithClassical has the initiator's classical attempt cross its
|
||||
// hybrid one: the hybrid msg2 is held back until the classical msg1 has reached
|
||||
// the responder, and the classical msg2 is lost, so the initiator commits to the
|
||||
// hybrid handshake.
|
||||
//
|
||||
// Arriving within the crossing window, the classical msg1 goes unanswered and
|
||||
// the responder ends up with the hybrid tunnel alone. Held past the window, as on
|
||||
// a very slow path, the responder completes it, and must still take the hybrid
|
||||
// tunnel when msg3 arrives even though the classical one is newer.
|
||||
func TestHybridRaceWithClassical(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
delay time.Duration
|
||||
answered bool
|
||||
}{
|
||||
{"within the window", 0, false},
|
||||
{"past the window", 500 * time.Millisecond, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Both trust the v2 form of the CA too, or the classical attempt could not complete.
|
||||
ca := newHybridCA(t)
|
||||
ca2, _ := ca.v2()
|
||||
myControl, theirControl, myVpn, theirVpn, _, _, r := newHybridPairWithCA(t, ca,
|
||||
withCA(pqConfig(true, true, false), ca.ca, ca2),
|
||||
withCA(pqConfig(false, true, false), ca.ca, ca2),
|
||||
)
|
||||
defer r.RenderFlow()
|
||||
|
||||
var heldMsg2 []*udp.Packet
|
||||
var classicalMsg1 *udp.Packet
|
||||
holdMsg2 := func(p *udp.Packet) bool {
|
||||
if h, fh := handshakeOf(p); h != nil && fh != nil && h.MessageCounter == 2 {
|
||||
heldMsg2 = append(heldMsg2, p.Copy())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, r.RouteForAllExitFuncOrTimeout(3*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if holdMsg2(p) {
|
||||
return router.Drop
|
||||
}
|
||||
if h, fh := handshakeOf(p); h != nil && fh == nil && h.MessageCounter == 1 {
|
||||
classicalMsg1 = p.Copy()
|
||||
return router.ExitNow
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "no classical attempt")
|
||||
|
||||
time.Sleep(tc.delay)
|
||||
r.InjectUDPPacket(myControl, theirControl, classicalMsg1)
|
||||
|
||||
// Lose any classical msg2, so the initiator only ever completes the hybrid
|
||||
// handshake. With msg2 held the initiator keeps retrying, and a later
|
||||
// classical retry may land past the window; only the crossing one counts.
|
||||
var classicalMsg2 int
|
||||
r.RouteForAllExitFuncOrTimeout(50*time.Millisecond, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if h, fh := handshakeOf(p); h != nil && fh == nil && h.MessageCounter == 1 {
|
||||
return router.Drop
|
||||
}
|
||||
if h, fh := handshakeOf(p); h != nil && fh == nil && h.MessageCounter == 2 {
|
||||
classicalMsg2++
|
||||
return router.Drop
|
||||
}
|
||||
if holdMsg2(p) {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
if tc.answered {
|
||||
require.Positive(t, classicalMsg2, "past the window the classical msg1 is answered")
|
||||
require.NotNil(t, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false))
|
||||
} else {
|
||||
require.Zero(t, classicalMsg2, "within the window the classical msg1 goes unanswered")
|
||||
require.Nil(t, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false))
|
||||
}
|
||||
|
||||
var recvErrors int
|
||||
for _, p := range heldMsg2 {
|
||||
r.InjectUDPPacket(theirControl, myControl, p)
|
||||
}
|
||||
require.True(t, routeUntilData(t, r, theirControl, 3*time.Second, func(p *udp.Packet, _ *nebula.Control) router.ExitType {
|
||||
if isType(p, header.RecvError) {
|
||||
recvErrors++
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "data never arrived")
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
|
||||
assert.Zero(t, recvErrors)
|
||||
mine := myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false)
|
||||
theirs := theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false)
|
||||
require.NotNil(t, mine)
|
||||
require.NotNil(t, theirs)
|
||||
assert.Equal(t, cert.Version3, mine.Cert.Version())
|
||||
assert.Equal(t, cert.Version3, theirs.Cert.Version(), "the responder's primary tunnel is the hybrid one")
|
||||
assert.Equal(t, mine.LocalIndex, theirs.RemoteIndex)
|
||||
if !tc.answered {
|
||||
assert.Len(t, theirControl.ListHostmapIndexes(false), 1, "and the only one")
|
||||
}
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridWrongResponder gives the initiator a stale address for its peer
|
||||
// that belongs to another v3 host now, so both answer its msg1. Their msg2
|
||||
// bursts interleave at the initiator and each must fill its own slot: the
|
||||
// tunnel to the right host comes up within two attempts, one if its answer
|
||||
// completes first and two if the other host's does, which the initiator
|
||||
// blocks and retries past as it would for a classical handshake. With require
|
||||
// there is no classical turn to fall back on, so a single slot that emptied
|
||||
// on every FragID change would run to the handshake timeout.
|
||||
func TestHybridWrongResponder(t *testing.T) {
|
||||
t.Parallel()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cfg m
|
||||
pqOnly bool
|
||||
}{
|
||||
{"taking turns", pqConfig(true, true, false), false},
|
||||
{"pq only", pqRequire(), true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
myControl, myVpn, myUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "me", "10.128.0.1/24", tc.cfg)
|
||||
theirControl, theirVpn, theirUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "them", "10.128.0.2/24", tc.cfg)
|
||||
otherControl, otherVpn, otherUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "other", "10.128.0.3/24", tc.cfg)
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), otherUdp)
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
|
||||
r := router.NewR(t, myControl, theirControl, otherControl)
|
||||
defer r.RenderFlow()
|
||||
myControl.Start()
|
||||
theirControl.Start()
|
||||
otherControl.Start()
|
||||
|
||||
var tally hybridTally
|
||||
msg1ToThem := 0
|
||||
msg2ByFragID := map[uint32]int{}
|
||||
var classical []string
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 5*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
tally.observe(p)
|
||||
if h, fh := handshakeOf(p); h != nil {
|
||||
switch {
|
||||
case fh == nil:
|
||||
classical = append(classical, fmt.Sprintf("counter=%d to=%s", h.MessageCounter, p.To))
|
||||
case h.MessageCounter == 1 && p.To == theirUdp:
|
||||
msg1ToThem++
|
||||
case h.MessageCounter == 2 && receiver == myControl:
|
||||
msg2ByFragID[fh.FragID]++
|
||||
}
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
t.Logf("msg1 fragments to them: %d, msg2 fragments by FragID: %v, classical: %v", msg1ToThem, msg2ByFragID, classical)
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.GreaterOrEqual(t, len(msg2ByFragID), 2, "both hosts answered")
|
||||
// A responder only resends msg2 when the initiator retries, so every
|
||||
// FragID staying at one burst means each interleaved answer completed in
|
||||
// its own slot. (The msg1 count is not a clean measure: a restart after
|
||||
// the wrong host answers leaves the old handshake's timer entry in place,
|
||||
// so the new one ticks twice, a few milliseconds apart.)
|
||||
for fragID, n := range msg2ByFragID {
|
||||
assert.LessOrEqual(t, n, 9+3, "responder %d had to resend msg2", fragID)
|
||||
}
|
||||
if tc.pqOnly {
|
||||
assert.Empty(t, classical, "require never offers a classical attempt")
|
||||
}
|
||||
|
||||
assertHostInfoPair(t, myUdp, theirUdp, myVpn, theirVpn, myControl, theirControl)
|
||||
assertTunnel(t, myVpn[0].Addr(), theirVpn[0].Addr(), myControl, theirControl, r)
|
||||
assert.Nil(t, myControl.GetHostInfoByVpnAddr(otherVpn[0].Addr(), false), "no tunnel to the other host")
|
||||
assert.Empty(t, myControl.ListHostmapIndexes(true), "no pending index may outlive the handshake")
|
||||
assert.Equal(t, cert.Version3, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false).Cert.Version(), "the hybrid handshake won")
|
||||
|
||||
myControl.Stop()
|
||||
theirControl.Stop()
|
||||
otherControl.Stop()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHybridMsg2LostDirect loses every msg2 fragment the responder sends
|
||||
// directly, as a responder answering from the wrong interface would. msg1 also
|
||||
// reaches it through a relay, and that copy must be answered on the relay as
|
||||
// soon as it completes, not refused because the direct copy was just answered.
|
||||
// The relay takes a few retry ticks to come up in this harness, so the check is
|
||||
// that the first copy of msg1 through the relay is enough once it does.
|
||||
func TestHybridMsg2LostDirect(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
useRelays := pqRequire()
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
amRelay := pqRequire()
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
myControl, myVpn, _, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpn, relayUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpn, theirUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "them ", "10.128.0.2/24", useRelays)
|
||||
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
myControl.InjectLightHouseAddr(relayVpn[0].Addr(), relayUdp)
|
||||
myControl.InjectRelays(theirVpn[0].Addr(), []netip.Addr{relayVpn[0].Addr()})
|
||||
relayControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
|
||||
r := router.NewR(t, myControl, relayControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
myControl.Start()
|
||||
relayControl.Start()
|
||||
theirControl.Start()
|
||||
|
||||
var relayedMsg1, directMsg2, relayedMsg2 int
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 10*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
h, fh := handshakeOf(p)
|
||||
if h == nil || fh == nil {
|
||||
return router.KeepRouting
|
||||
}
|
||||
outer := &header.H{}
|
||||
relayed := outer.Parse(p.Data) == nil && outer.Type == header.Message && outer.Subtype == header.MessageRelay
|
||||
switch {
|
||||
case h.MessageCounter == 1 && relayed && receiver == theirControl:
|
||||
relayedMsg1++
|
||||
case h.MessageCounter == 2 && !relayed && p.From == theirUdp && receiver == myControl:
|
||||
directMsg2++
|
||||
return router.Drop
|
||||
case h.MessageCounter == 2 && relayed && receiver == myControl:
|
||||
relayedMsg2++
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
assert.GreaterOrEqual(t, directMsg2, 9, "the direct answer was sent and lost")
|
||||
assert.GreaterOrEqual(t, relayedMsg2, 9, "the relayed copy of msg1 got its own answer")
|
||||
assert.LessOrEqual(t, relayedMsg1, 7+3, "the first copy of msg1 through the relay is answered, no relayed retry is needed")
|
||||
r.RenderHostmaps("Final hostmaps", myControl, relayControl, theirControl)
|
||||
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
|
||||
// TestHybridOneWayDirect loses everything the responder sends directly, not
|
||||
// just msg2, so only the relay carries anything back. msg3 comes by the relay,
|
||||
// since that is where msg2 got through, and the responder must then send by the
|
||||
// relay too: its confirmation, and its replies. Keeping the direct address it
|
||||
// learned from msg1 would lose both, and the initiator would close the tunnel as
|
||||
// never confirmed.
|
||||
func TestHybridOneWayDirect(t *testing.T) {
|
||||
t.Parallel()
|
||||
ca := newHybridCA(t)
|
||||
useRelays := pqRequire()
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
// The relay takes about a second to come up in this harness; 8 retries make the
|
||||
// handshake timeout 3.6s, which the end of the test waits out.
|
||||
useRelays["handshakes"].(m)["retries"] = 8
|
||||
amRelay := pqRequire()
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
myControl, myVpn, _, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpn, relayUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpn, theirUdp, _ := newSimpleServer(cert.Version3, ca.ca, ca.key, "them ", "10.128.0.2/24", useRelays)
|
||||
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
myControl.InjectLightHouseAddr(relayVpn[0].Addr(), relayUdp)
|
||||
myControl.InjectRelays(theirVpn[0].Addr(), []netip.Addr{relayVpn[0].Addr()})
|
||||
relayControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
|
||||
r := router.NewR(t, myControl, relayControl, theirControl)
|
||||
defer r.RenderFlow()
|
||||
myControl.Start()
|
||||
relayControl.Start()
|
||||
theirControl.Start()
|
||||
|
||||
oneWay := func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if p.From == theirUdp && receiver == myControl {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
}
|
||||
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("Hi from me")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 10*time.Second, oneWay), "tunnel never came up")
|
||||
assertUdpPacket(t, []byte("Hi from me"), theirControl.GetFromTun(true), myVpn[0].Addr(), theirVpn[0].Addr(), 80, 80)
|
||||
|
||||
theirControl.InjectTunPacket(BuildTunUDPPacket(myVpn[0].Addr(), 80, theirVpn[0].Addr(), 80, []byte("Hi from them")))
|
||||
require.True(t, routeUntilData(t, r, myControl, 3*time.Second, oneWay), "the reply never came back")
|
||||
assertUdpPacket(t, []byte("Hi from them"), myControl.GetFromTun(true), theirVpn[0].Addr(), myVpn[0].Addr(), 80, 80)
|
||||
|
||||
// Well past the handshake timeout, the initiator must still have the tunnel.
|
||||
r.RouteForAllExitFuncOrTimeout(4*time.Second, oneWay)
|
||||
mine := myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false)
|
||||
require.NotNil(t, mine, "the initiator heard back, so it kept the tunnel")
|
||||
assert.Equal(t, cert.Version3, mine.Cert.Version())
|
||||
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//go:build e2e_testing
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/e2e/router"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// relayedHybridTunnel brings up a hybrid tunnel whose msg2 completes by the
|
||||
// relay: every direct msg2 fragment is lost, and drop decides what else is. It
|
||||
// returns the controls with the tunnel up and the first packet delivered.
|
||||
func relayedHybridTunnel(t *testing.T, drop func(p *udp.Packet, receiver *nebula.Control, them netip.AddrPort, me *nebula.Control) bool) (myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, myUdp, theirUdp netip.AddrPort, r *router.R) {
|
||||
t.Helper()
|
||||
ca := newHybridCA(t)
|
||||
useRelays := pqRequire()
|
||||
useRelays["relay"] = m{"use_relays": true}
|
||||
useRelays["counters"] = m{"try_promote": 5}
|
||||
amRelay := pqRequire()
|
||||
amRelay["relay"] = m{"am_relay": true}
|
||||
var relayControl *nebula.Control
|
||||
var relayVpn []netip.Prefix
|
||||
var relayUdp netip.AddrPort
|
||||
myControl, myVpn, myUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "me ", "10.128.0.1/24", useRelays)
|
||||
relayControl, relayVpn, relayUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "relay ", "10.128.0.128/24", amRelay)
|
||||
theirControl, theirVpn, theirUdp, _ = newSimpleServer(cert.Version3, ca.ca, ca.key, "them ", "10.128.0.2/24", useRelays)
|
||||
myControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
myControl.InjectLightHouseAddr(relayVpn[0].Addr(), relayUdp)
|
||||
myControl.InjectRelays(theirVpn[0].Addr(), []netip.Addr{relayVpn[0].Addr()})
|
||||
relayControl.InjectLightHouseAddr(theirVpn[0].Addr(), theirUdp)
|
||||
r = router.NewR(t, myControl, relayControl, theirControl)
|
||||
myControl.Start()
|
||||
relayControl.Start()
|
||||
theirControl.Start()
|
||||
t.Cleanup(func() {
|
||||
myControl.Stop()
|
||||
relayControl.Stop()
|
||||
theirControl.Stop()
|
||||
})
|
||||
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("first")))
|
||||
require.True(t, routeUntilData(t, r, theirControl, 10*time.Second, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
outer := &header.H{}
|
||||
relayed := outer.Parse(p.Data) == nil && outer.Type == header.Message && outer.Subtype == header.MessageRelay
|
||||
if h, fh := handshakeOf(p); h != nil && fh != nil && h.MessageCounter == 2 && !relayed && p.From == theirUdp && receiver == myControl {
|
||||
return router.Drop
|
||||
}
|
||||
if drop(p, receiver, theirUdp, myControl) {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
}), "tunnel never came up")
|
||||
theirControl.GetFromTun(true)
|
||||
return
|
||||
}
|
||||
|
||||
// exchange sends n packets each way, routing with drop, and reports how many
|
||||
// arrived in each direction.
|
||||
func exchange(t *testing.T, r *router.R, myControl, theirControl *nebula.Control, myVpn, theirVpn []netip.Prefix, theirUdp netip.AddrPort, n int, drop func(p *udp.Packet, receiver *nebula.Control, them netip.AddrPort, me *nebula.Control) bool) (toThem, toMe int) {
|
||||
t.Helper()
|
||||
route := func(to *nebula.Control) bool {
|
||||
return routeUntilData(t, r, to, 300*time.Millisecond, func(p *udp.Packet, receiver *nebula.Control) router.ExitType {
|
||||
if drop(p, receiver, theirUdp, myControl) {
|
||||
return router.Drop
|
||||
}
|
||||
return router.KeepRouting
|
||||
})
|
||||
}
|
||||
for range n {
|
||||
myControl.InjectTunPacket(BuildTunUDPPacket(theirVpn[0].Addr(), 80, myVpn[0].Addr(), 80, []byte("to them")))
|
||||
if route(theirControl) {
|
||||
theirControl.GetFromTun(true)
|
||||
toThem++
|
||||
}
|
||||
theirControl.InjectTunPacket(BuildTunUDPPacket(myVpn[0].Addr(), 80, theirVpn[0].Addr(), 80, []byte("to me")))
|
||||
if route(myControl) {
|
||||
myControl.GetFromTun(true)
|
||||
toMe++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func noDrop(*udp.Packet, *nebula.Control, netip.AddrPort, *nebula.Control) bool { return false }
|
||||
|
||||
// TestHybridRelayPromotion has msg2 complete by the relay although the direct
|
||||
// path works both ways, as it often does on real networks where the tunnel to
|
||||
// the relay is already up and the direct path still needs a punch. Both ends
|
||||
// start relayed, and the usual promotion moves them to direct.
|
||||
//
|
||||
// With the direct path working only toward the responder, promotion's direct
|
||||
// probe makes the responder roam onto it and lose its replies, hybrid or
|
||||
// classical alike: roaming on receipt assumes a path works both ways. Roam path
|
||||
// validation (claude/roam-path-validation) would hold the responder on the relay.
|
||||
func TestHybridRelayPromotion(t *testing.T) {
|
||||
t.Parallel()
|
||||
myControl, theirControl, myVpn, theirVpn, myUdp, theirUdp, r := relayedHybridTunnel(t, noDrop)
|
||||
defer r.RenderFlow()
|
||||
|
||||
theirs := theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false)
|
||||
require.NotNil(t, theirs)
|
||||
assert.False(t, theirs.CurrentRemote.IsValid(), "msg3 came by the relay, so the responder starts relayed")
|
||||
|
||||
toThem, toMe := exchange(t, r, myControl, theirControl, myVpn, theirVpn, theirUdp, 20, noDrop)
|
||||
assert.Equal(t, 20, toThem)
|
||||
assert.Equal(t, 20, toMe)
|
||||
assert.Equal(t, theirUdp, myControl.GetHostInfoByVpnAddr(theirVpn[0].Addr(), false).CurrentRemote, "the initiator promoted to direct")
|
||||
assert.Equal(t, myUdp, theirControl.GetHostInfoByVpnAddr(myVpn[0].Addr(), false).CurrentRemote, "the responder promoted to direct")
|
||||
}
|
||||
+13
-4
@@ -4,10 +4,17 @@
|
||||
# PKI defines the location of credentials for this node. Each of these can also be inlined by using the yaml ": |" syntax.
|
||||
pki:
|
||||
# The CAs that are accepted by this node. Must contain one or more certificates created by 'nebula-cert ca'
|
||||
# A version 3 CA only accepts version 3 certificates, which only post-quantum hybrid handshakes use. To also
|
||||
# accept version 2 certificates from it, list its v2 form as well (nebula-cert print shows its v2Fingerprint).
|
||||
# Leaving the v2 form out is how a node requires post-quantum authentication.
|
||||
ca: /etc/nebula/ca.crt
|
||||
# cert may hold a version 3 certificate, which also serves as its v2 form for classical handshakes. key then
|
||||
# holds the version 3 key from 'nebula-cert keygen -version 3' or 'nebula-cert sign'.
|
||||
cert: /etc/nebula/host.crt
|
||||
key: /etc/nebula/host.key
|
||||
# blocklist is a list of certificate fingerprints that we will refuse to talk to
|
||||
# A version 3 certificate has two fingerprints, its own and its v2 form's. Blocking the v2 one blocks both,
|
||||
# blocking the v3 one leaves the v2 form usable in classical handshakes, so list both.
|
||||
#blocklist:
|
||||
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
||||
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
||||
@@ -418,9 +425,11 @@ logging:
|
||||
# after receiving the response for lighthouse queries
|
||||
#trigger_buffer: 64
|
||||
|
||||
# pq enables handshakes that mix an ephemeral ML-KEM-1024 key exchange into the session keys, protecting
|
||||
# recorded traffic against a future quantum computer. Authentication is unchanged. These handshakes are too
|
||||
# large for one packet and travel as fragments with forward error correction.
|
||||
# pq enables hybrid handshakes: ML-KEM-1024 alongside the classical key exchange, so recorded traffic stays
|
||||
# secret against a future quantum computer, and authentication by the version 3 certificates' ML-KEM-1024 keys.
|
||||
# Both ends need a version 3 certificate in pki.cert; without one these settings are ignored with a warning, and
|
||||
# require is refused. These handshakes are too large for one packet and travel as fragments with forward error
|
||||
# correction.
|
||||
#pq:
|
||||
# initiate starts post-quantum handshakes. Attempts alternate between post-quantum and classical until one is
|
||||
# answered, so peers that do not support them still connect.
|
||||
@@ -428,7 +437,7 @@ logging:
|
||||
# accept answers post-quantum handshakes from peers.
|
||||
#accept: false
|
||||
# require makes every handshake post-quantum: it implies initiate and accept, never offers a classical handshake
|
||||
# and refuses classical handshakes from peers. Only enable it once every host can speak post-quantum handshakes.
|
||||
# and refuses classical handshakes from peers. Only enable it once every host has a version 3 certificate.
|
||||
#require: false
|
||||
# sticky never falls back to a classical handshake with a peer that has completed a post-quantum one since
|
||||
# nebula started, which defeats an attacker who drops post-quantum handshakes to force a downgrade.
|
||||
|
||||
@@ -764,6 +764,14 @@ func (fc *FirewallCA) match(p firewall.Packet, c *cert.CachedCertificate, caPool
|
||||
return false
|
||||
}
|
||||
|
||||
// A version 3 certificate names its CA by the fingerprint of the CA's v2 form,
|
||||
// which is matched above. A rule may also use the v3 CA's own fingerprint.
|
||||
if c.Certificate.Version() == cert.Version3 {
|
||||
if t, ok := fc.CAShas[s.Fingerprint]; ok && t.match(p, c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return fc.CANames[s.Certificate.Name()].match(p, c)
|
||||
}
|
||||
|
||||
|
||||
+58
-1
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/firewall"
|
||||
"github.com/slackhq/nebula/iputil"
|
||||
@@ -1256,7 +1257,7 @@ func TestNewFirewallFromConfig(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
// Test a bad rule definition
|
||||
c := &dummyCert{}
|
||||
cs, err := newCertState(cert.Version2, nil, c, false, cert.Curve_CURVE25519, nil, "aes")
|
||||
cs, err := newCertState(cert.Version2, nil, c, nil, false, cert.Curve_CURVE25519, nil, "aes")
|
||||
require.NoError(t, err)
|
||||
|
||||
conf := config.NewC(test.NewLogger())
|
||||
@@ -1745,3 +1746,59 @@ func resetConntrack(fw *Firewall) {
|
||||
fw.Conntrack.Conns = map[firewall.Packet]*conn{}
|
||||
fw.Conntrack.Unlock()
|
||||
}
|
||||
|
||||
// A version 3 certificate's CA answers to both its fingerprints in ca_sha rules: the v2 form's, which is what the
|
||||
// certificate names as issuer, and its own. A v2 certificate only to the v2 one.
|
||||
func TestFirewall_CAShaV3(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version3, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
host, _, _, _ := cert_test.NewTestCert(cert.Version3, cert.Curve_CURVE25519, ca, caKey, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("1.2.3.4/24")}, nil, nil)
|
||||
cp := cert.NewCAPool()
|
||||
require.NoError(t, cp.AddCA(ca))
|
||||
require.NoError(t, cp.AddCA(cert.V2Form(ca)))
|
||||
v3Sha, err := ca.Fingerprint()
|
||||
require.NoError(t, err)
|
||||
v2Sha, err := cert.V2Form(ca).Fingerprint()
|
||||
require.NoError(t, err)
|
||||
|
||||
myVpnNetworksTable := new(bart.Lite)
|
||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("1.1.1.1/8"))
|
||||
p := firewall.Packet{
|
||||
LocalAddr: netip.MustParseAddr("1.2.3.4"),
|
||||
RemoteAddr: netip.MustParseAddr("1.2.3.4"),
|
||||
LocalPort: 10,
|
||||
RemotePort: 90,
|
||||
Protocol: iputil.IPProtocolUDP,
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
c cert.Certificate
|
||||
caSha string
|
||||
match bool
|
||||
}{
|
||||
{"v3 by v2 sha", host, v2Sha, true},
|
||||
{"v3 by v3 sha", host, v3Sha, true},
|
||||
{"v2 form by v2 sha", cert.V2Form(host), v2Sha, true},
|
||||
{"v2 form by v3 sha", cert.V2Form(host), v3Sha, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cc, err := cp.VerifyCertificate(time.Now(), tc.c)
|
||||
require.NoError(t, err)
|
||||
h := HostInfo{
|
||||
ConnectionState: &ConnectionState{peerCert: cc},
|
||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("1.2.3.4")},
|
||||
}
|
||||
h.buildNetworks(myVpnNetworksTable, tc.c)
|
||||
|
||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, tc.c)
|
||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, nil, "", "", "", "", tc.caSha))
|
||||
err = fw.Drop(p, true, &h, cp, nil)
|
||||
if tc.match {
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
require.ErrorIs(t, err, ErrNoMatchingRule)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
module github.com/slackhq/nebula
|
||||
|
||||
go 1.26.0
|
||||
go 1.27.0
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2
|
||||
filippo.io/bigmod v0.1.0
|
||||
github.com/DefinedNet/netlink v1.3.2-dn.1
|
||||
github.com/DefinedNet/noise v0.0.0-00010101000000-000000000000
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
|
||||
github.com/armon/go-radix v1.0.0
|
||||
github.com/flynn/noise v1.1.0
|
||||
github.com/gaissmai/bart v0.29.0
|
||||
github.com/gogo/protobuf v1.3.2
|
||||
github.com/google/gopacket v1.1.19
|
||||
@@ -47,3 +47,5 @@ require (
|
||||
github.com/vishvananda/netns v0.0.5 // indirect
|
||||
golang.org/x/time v0.5.0 // indirect
|
||||
)
|
||||
|
||||
replace github.com/DefinedNet/noise => /home/jack/work/git/DefinedNet-noise
|
||||
@@ -23,8 +23,6 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg=
|
||||
github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
|
||||
github.com/gaissmai/bart v0.29.0 h1:wO6HGE8g9YE0Wm0bCpYxwRzfQ4+fbJKOhL64e5ACGCI=
|
||||
github.com/gaissmai/bart v0.29.0/go.mod h1:GREWQfTLRWz/c5FTOsIw+KkscuFkIV5t8Rp7Nd1Td5c=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
@@ -154,7 +152,6 @@ golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnf
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
|
||||
@@ -170,7 +167,6 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
|
||||
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -192,12 +188,10 @@ golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
|
||||
+43
-19
@@ -1,9 +1,10 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"crypto/mlkem"
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
)
|
||||
|
||||
@@ -11,42 +12,65 @@ import (
|
||||
// at a given cert version. Version and Curve are read from Cert; the public
|
||||
// half of the static keypair likewise comes from Cert.PublicKey().
|
||||
type Credential struct {
|
||||
Cert cert.Certificate // the certificate
|
||||
Bytes []byte // pre-marshaled certificate bytes
|
||||
privateKey []byte // static private key (public half lives in Cert)
|
||||
cipherSuite noise.CipherSuite // pre-built cipher suite (DH + cipher + hash)
|
||||
Cert cert.Certificate // the certificate
|
||||
Bytes []byte // pre-marshaled certificate bytes
|
||||
privateKey []byte // static private key (public half lives in Cert)
|
||||
publicKey []byte // static public key, the classical half for a v3 Cert
|
||||
kemKey noise.KEMKey // static KEM keypair of the Cert's suite, only for a v3 Cert
|
||||
kemDK *mlkem.DecapsulationKey1024 // kemKey expanded, when the suite's KEM is ML-KEM-1024
|
||||
cipherSuite noise.CipherSuite // pre-built cipher suite (DH + cipher + hash)
|
||||
}
|
||||
|
||||
// NewCredential creates a Credential with all material needed for handshake
|
||||
// participation. The cipherSuite should be pre-built by the caller with the
|
||||
// appropriate DH function, cipher, and hash.
|
||||
//
|
||||
// For a version 3 certificate privateKey is the composite private key,
|
||||
// classical || the seed of its suite's KEM, matching the composite
|
||||
// Cert.PublicKey().
|
||||
func NewCredential(
|
||||
c cert.Certificate,
|
||||
hsBytes []byte,
|
||||
privateKey []byte,
|
||||
cipherSuite noise.CipherSuite,
|
||||
) *Credential {
|
||||
return &Credential{
|
||||
hc := &Credential{
|
||||
Cert: c,
|
||||
Bytes: hsBytes,
|
||||
privateKey: privateKey,
|
||||
publicKey: c.PublicKey(),
|
||||
cipherSuite: cipherSuite,
|
||||
}
|
||||
if suite := cert.PQSuiteOf(c); suite != cert.PQSuiteUnknown {
|
||||
// The pki checked the private key against the certificate, so both split.
|
||||
hc.publicKey, hc.kemKey.Public, _ = suite.SplitPublicKey(false, c.PublicKey())
|
||||
hc.privateKey, hc.kemKey.Private, _ = suite.SplitPrivateKey(false, privateKey)
|
||||
// Expand the static KEM key once rather than in every handshake.
|
||||
if st, ok := HybridSubtype(suite); ok && subtypeInfos[st].kem == KEMMLKEM1024 {
|
||||
hc.kemDK, _ = mlkem.NewDecapsulationKey1024(hc.kemKey.Private)
|
||||
}
|
||||
}
|
||||
return hc
|
||||
}
|
||||
|
||||
// buildHandshakeState creates a noise.HandshakeState from this credential.
|
||||
// pskPlacement selects the noise psk modifier; 0 means none. A psk for
|
||||
// placements 2 and up is supplied later with SetPresharedKey.
|
||||
func (hc *Credential) buildHandshakeState(initiator bool, pattern noise.HandshakePattern, pskPlacement int) (*noise.HandshakeState, error) {
|
||||
return noise.NewHandshakeState(noise.Config{
|
||||
CipherSuite: hc.cipherSuite,
|
||||
Random: rand.Reader,
|
||||
Pattern: pattern,
|
||||
Initiator: initiator,
|
||||
StaticKeypair: noise.DHKey{Private: hc.privateKey, Public: hc.Cert.PublicKey()},
|
||||
PresharedKey: []byte{},
|
||||
PresharedKeyPlacement: pskPlacement,
|
||||
})
|
||||
// buildHandshakeState creates a noise.HandshakeState from this credential. A
|
||||
// hybrid pattern also gets its KEM and the static KEM key.
|
||||
func (hc *Credential) buildHandshakeState(initiator bool, info subtypeInfo) (*noise.HandshakeState, error) {
|
||||
cfg := noise.Config{
|
||||
CipherSuite: hc.cipherSuite,
|
||||
Random: rand.Reader,
|
||||
Pattern: info.pattern,
|
||||
Initiator: initiator,
|
||||
StaticKeypair: noise.DHKey{Private: hc.privateKey, Public: hc.publicKey},
|
||||
}
|
||||
if info.kem != nil {
|
||||
cfg.KEMFunc = info.kem
|
||||
cfg.StaticKEMKeypair = hc.kemKey
|
||||
if info.kem == KEMMLKEM1024 {
|
||||
cfg.KEMFunc = &mlkem1024Keys{static: hc.kemDK, staticSeed: hc.kemKey.Private}
|
||||
}
|
||||
}
|
||||
return noise.NewHandshakeState(cfg)
|
||||
}
|
||||
|
||||
// GetCredentialFunc returns the handshake credential for the given version,
|
||||
|
||||
@@ -19,4 +19,6 @@ var (
|
||||
ErrAsymmetricCipherKeys = errors.New("noise produced only one cipher key")
|
||||
ErrMultiMessageUnsupported = errors.New("multi-message handshake patterns are not yet supported by the manager")
|
||||
ErrSubtypeMismatch = errors.New("packet subtype does not match handshake machine subtype")
|
||||
ErrCertVersionMismatch = errors.New("handshake subtype does not allow this certificate version")
|
||||
ErrPQSuiteMismatch = errors.New("handshake subtype does not use the KEM of this certificate's post-quantum suite")
|
||||
)
|
||||
+36
-8
@@ -11,6 +11,7 @@ package fec
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// MaxSymbols is the number of distinct symbols, data and repair together, one
|
||||
@@ -57,18 +58,20 @@ type Encoder struct {
|
||||
data [][]byte
|
||||
}
|
||||
|
||||
// NewEncoder copies msg into padded data symbols.
|
||||
// NewEncoder splits msg into data symbols. They alias msg, all but a padded
|
||||
// last symbol, so msg must not change while the Encoder is in use.
|
||||
func NewEncoder(msg []byte, maxSymbolSize int) (*Encoder, error) {
|
||||
l, err := NewLayout(len(msg), maxSymbolSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
buf := make([]byte, l.K*l.SymbolSize)
|
||||
copy(buf, msg)
|
||||
data := make([][]byte, l.K)
|
||||
for i := range data {
|
||||
data[i] = buf[i*l.SymbolSize : (i+1)*l.SymbolSize]
|
||||
data[i] = msg[i*l.SymbolSize : min((i+1)*l.SymbolSize, len(msg))]
|
||||
}
|
||||
if last := data[l.K-1]; len(last) < l.SymbolSize {
|
||||
data[l.K-1] = append(make([]byte, 0, l.SymbolSize), last...)[:l.SymbolSize]
|
||||
}
|
||||
return &Encoder{layout: l, data: data}, nil
|
||||
}
|
||||
@@ -98,6 +101,21 @@ func (e *Encoder) Symbol(dst []byte, index int) ([]byte, error) {
|
||||
// Decoder collects symbols for one message until it can reconstruct it.
|
||||
// It stores at most K symbols, so its memory is bounded by the layout no matter
|
||||
// how many symbols arrive.
|
||||
//
|
||||
// TODO(in-place decode): for receivers that already hold state for the message,
|
||||
// the initiator's msg2 slots and a pending responder's msg3, store into one
|
||||
// buffer of K*SymbolSize (plus room for the Nebula header) allocated from the
|
||||
// layout: data symbol i at offset i*SymbolSize, repair symbols parked in the
|
||||
// slots of data symbols not seen yet (moved to another empty slot if that data
|
||||
// symbol arrives; one always exists while fewer than K are held). Decode then
|
||||
// folds the known columns into each parked repair symbol in place and runs
|
||||
// Gauss-Jordan across those rows in place; a Cauchy submatrix needs no
|
||||
// pivoting, so each solution lands in the slot of its own column and the
|
||||
// buffer is the packet. That removes the per-symbol copies, about 10KB and a
|
||||
// dozen allocations per msg2, at the
|
||||
// cost of holding K*SymbolSize from the first fragment and destroying the
|
||||
// input on a failed decode. It is not for the responder's msg1 table, which
|
||||
// must never allocate from a claimed size.
|
||||
type Decoder struct {
|
||||
layout Layout
|
||||
have [MaxSymbols]bool
|
||||
@@ -128,6 +146,11 @@ func (d *Decoder) Has(index int) bool {
|
||||
return index >= 0 && index < MaxSymbols && d.have[index]
|
||||
}
|
||||
|
||||
// Seen returns which symbol indexes are held.
|
||||
func (d *Decoder) Seen() [MaxSymbols]bool {
|
||||
return d.have
|
||||
}
|
||||
|
||||
// Ready reports whether enough symbols have arrived to decode.
|
||||
func (d *Decoder) Ready() bool {
|
||||
return len(d.syms) >= d.layout.K
|
||||
@@ -150,19 +173,24 @@ func (d *Decoder) Add(index int, sym []byte) (bool, error) {
|
||||
return d.Ready(), nil
|
||||
}
|
||||
|
||||
// Decode reconstructs the message from the stored symbols.
|
||||
func (d *Decoder) Decode() ([]byte, error) {
|
||||
// Decode reconstructs the message from the stored symbols and appends it to
|
||||
// dst. Decoding needs the padding of the last symbol too, so dst has to have
|
||||
// room for K*SymbolSize bytes or it is grown to.
|
||||
func (d *Decoder) Decode(dst []byte) ([]byte, error) {
|
||||
if !d.Ready() {
|
||||
return nil, ErrNotEnough
|
||||
}
|
||||
l := d.layout
|
||||
|
||||
out := make([]byte, l.K*l.SymbolSize)
|
||||
start := len(dst)
|
||||
dst = slices.Grow(dst, l.K*l.SymbolSize)[:start+l.K*l.SymbolSize]
|
||||
out := dst[start:]
|
||||
var missing, repair []int
|
||||
for i := range l.K {
|
||||
if s, ok := d.syms[i]; ok {
|
||||
copy(out[i*l.SymbolSize:], s)
|
||||
} else {
|
||||
clear(out[i*l.SymbolSize : (i+1)*l.SymbolSize])
|
||||
missing = append(missing, i)
|
||||
}
|
||||
}
|
||||
@@ -212,5 +240,5 @@ func (d *Decoder) Decode() ([]byte, error) {
|
||||
return nil, ErrCorrupt
|
||||
}
|
||||
}
|
||||
return out[:l.MsgLen], nil
|
||||
return dst[:start+l.MsgLen], nil
|
||||
}
|
||||
@@ -93,9 +93,17 @@ func decodeWith(t *testing.T, enc *Encoder, msgLen, maxSym int, indexes []int) [
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.True(t, dec.Ready())
|
||||
out, err := dec.Decode()
|
||||
// Decode after a prefix, into capacity holding garbage, which must neither
|
||||
// disturb the prefix nor leak into the message.
|
||||
dst := make([]byte, 3, 3+dec.Layout().K*dec.Layout().SymbolSize)
|
||||
for i := range dst[:cap(dst)] {
|
||||
dst[:cap(dst)][i] = 0xa5
|
||||
}
|
||||
out, err := dec.Decode(dst)
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
require.Equal(t, []byte{0xa5, 0xa5, 0xa5}, out[:3])
|
||||
require.Equal(t, &dst[:1][0], &out[:1][0], "decoded in place")
|
||||
return out[3:]
|
||||
}
|
||||
|
||||
// TestExhaustiveSubsets decodes every k-subset of the first k+m symbols for
|
||||
@@ -156,7 +164,7 @@ func TestDecoderBounds(t *testing.T) {
|
||||
dec, err := NewDecoder(3000, 1176)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = dec.Decode()
|
||||
_, err = dec.Decode(nil)
|
||||
require.ErrorIs(t, err, ErrNotEnough)
|
||||
|
||||
_, err = dec.Add(-1, make([]byte, 1000))
|
||||
@@ -190,7 +198,7 @@ func TestDecoderBounds(t *testing.T) {
|
||||
require.True(t, ready)
|
||||
require.Len(t, dec.syms, 3)
|
||||
|
||||
out, err := dec.Decode()
|
||||
out, err := dec.Decode(nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, msg, out)
|
||||
}
|
||||
@@ -207,7 +215,7 @@ func TestCorruptPadding(t *testing.T) {
|
||||
_, err = dec.Add(i, s)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
_, err = dec.Decode()
|
||||
_, err = dec.Decode(nil)
|
||||
require.ErrorIs(t, err, ErrCorrupt)
|
||||
}
|
||||
|
||||
@@ -274,7 +282,7 @@ func FuzzDecoder(f *testing.F) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
out, err := dec.Decode()
|
||||
out, err := dec.Decode(nil)
|
||||
if err == nil {
|
||||
require.Len(t, out, int(msgLen))
|
||||
}
|
||||
@@ -311,7 +319,7 @@ func BenchmarkDecode(b *testing.B) {
|
||||
for i, x := range idx {
|
||||
_, _ = dec.Add(x, syms[i])
|
||||
}
|
||||
if _, err := dec.Decode(); err != nil {
|
||||
if _, err := dec.Decode(nil); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,9 +50,10 @@ func (a *Assembly) wouldStore(h Header, sym []byte) int {
|
||||
return len(sym)
|
||||
}
|
||||
|
||||
// Decode reconstructs the message. It requires Add to have reported ready.
|
||||
func (a *Assembly) Decode() ([]byte, error) {
|
||||
return a.dec.Decode()
|
||||
// Decode reconstructs the message and appends it to dst, see fec.Decoder.Decode.
|
||||
// It requires Add to have reported ready.
|
||||
func (a *Assembly) Decode(dst []byte) ([]byte, error) {
|
||||
return a.dec.Decode(dst)
|
||||
}
|
||||
|
||||
// Stored returns the number of symbol bytes held.
|
||||
|
||||
@@ -2,6 +2,7 @@ package fragment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -240,6 +241,8 @@ func TestLossy(t *testing.T) {
|
||||
// duplicate can complete one again; the handshake layer
|
||||
// recognises the repeat.
|
||||
require.True(t, bytes.Equal(msg, res.Msg))
|
||||
require.Len(t, res.Packet, header.Len+len(msg))
|
||||
require.Equal(t, &res.Packet[header.Len], &res.Msg[0], "Msg follows room for a header")
|
||||
got = res
|
||||
}
|
||||
checkInvariants(t, tb)
|
||||
@@ -513,3 +516,167 @@ func FuzzTable(f *testing.F) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestTableAnswered sends many large messages from one source the way a responder
|
||||
// sees back to back handshakes: each attempt's data fragments complete the
|
||||
// message and its repair fragments trail. Remembering answered messages keeps the
|
||||
// stragglers from piling up against the source quota, and a retry with fresh
|
||||
// symbols still reports the message again.
|
||||
func TestTableAnswered(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(3, 3))
|
||||
tb := NewTable[testKey, string](testConfig())
|
||||
now := time.Unix(1000, 0)
|
||||
const msgLen = 8009 // a hybrid msg1: K=7 data symbols, 3 repair
|
||||
|
||||
sendAll := func(key testKey, pkts [][]byte) []*Result {
|
||||
var out []*Result
|
||||
for _, p := range pkts {
|
||||
_, h, sym := parse(t, p)
|
||||
res, err := tb.Add(key, key.src, now, h, sym)
|
||||
require.NoError(t, err)
|
||||
if res != nil {
|
||||
out = append(out, res)
|
||||
}
|
||||
checkInvariants(t, tb)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
for i := range 3 * testConfig().MaxPerSource {
|
||||
msg := randMsg(r, msgLen)
|
||||
key := testKey{"a", uint32(i + 1)}
|
||||
s, err := NewSender(msg, testSubtype, 0, 1, key.fragID)
|
||||
require.NoError(t, err)
|
||||
data, repair, err := s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, data, 7)
|
||||
require.Len(t, repair, 3)
|
||||
|
||||
res := sendAll(key, data)
|
||||
require.Len(t, res, 1, "message %d was refused", i)
|
||||
require.Equal(t, msg, res[0].Msg)
|
||||
tb.Answered(key, res[0], now)
|
||||
|
||||
assert.Empty(t, sendAll(key, repair), "stragglers are not a new message")
|
||||
assert.Zero(t, tb.Len(), "and hold no entry")
|
||||
now = now.Add(100 * time.Millisecond)
|
||||
}
|
||||
|
||||
// A retry offers fresh symbols, and once K of them arrive it is a repeat.
|
||||
msg := randMsg(r, msgLen)
|
||||
key := testKey{"b", 99}
|
||||
s, err := NewSender(msg, testSubtype, 0, 1, key.fragID)
|
||||
require.NoError(t, err)
|
||||
data, repair, err := s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
res := sendAll(key, data)
|
||||
require.Len(t, res, 1)
|
||||
tb.Answered(key, res[0], now)
|
||||
require.Empty(t, sendAll(key, repair))
|
||||
|
||||
data, repair, err = s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
res = sendAll(key, append(data, repair...))
|
||||
require.Len(t, res, 1)
|
||||
assert.True(t, res[0].Repeat)
|
||||
assert.Nil(t, res[0].Msg)
|
||||
assert.Equal(t, sha256.Sum256(msg), res[0].Hash)
|
||||
assert.Positive(t, res[0].Received)
|
||||
|
||||
// Forgotten, the message is reassembled from scratch again.
|
||||
tb.Forget(key)
|
||||
data, _, err = s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
res = sendAll(key, data)
|
||||
require.Len(t, res, 1)
|
||||
assert.False(t, res[0].Repeat)
|
||||
assert.Equal(t, msg, res[0].Msg)
|
||||
|
||||
// Answered messages expire with the TTL like entries do.
|
||||
tb.Answered(key, res[0], now)
|
||||
tb.Expire(now.Add(time.Hour))
|
||||
tb.mu.Lock()
|
||||
assert.Empty(t, tb.answered)
|
||||
tb.mu.Unlock()
|
||||
}
|
||||
|
||||
// TestTableRepeatInterval checks that an answered message is reported as a
|
||||
// repeat at most once per RepeatInterval on one key, while another key, a
|
||||
// second path the same message arrives by, keeps its own clock.
|
||||
func TestTableRepeatInterval(t *testing.T) {
|
||||
r := rand.New(rand.NewPCG(4, 4))
|
||||
cfg := testConfig()
|
||||
cfg.RepeatInterval = 100 * time.Millisecond
|
||||
tb := NewTable[testKey, string](cfg)
|
||||
now := time.Unix(1000, 0)
|
||||
msg := randMsg(r, 8009) // K=7, 3 repair
|
||||
|
||||
attempt := func(s *Sender) [][]byte {
|
||||
data, repair, err := s.Attempt(DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
return append(data, repair...)
|
||||
}
|
||||
repeats := func(key testKey, pkts [][]byte) int {
|
||||
n := 0
|
||||
for _, p := range pkts {
|
||||
_, h, sym := parse(t, p)
|
||||
res, err := tb.Add(key, key.src, now, h, sym)
|
||||
require.NoError(t, err)
|
||||
if res != nil {
|
||||
require.True(t, res.Repeat)
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
answer := func(key testKey, s *Sender) {
|
||||
var res *Result
|
||||
for _, p := range attempt(s) {
|
||||
_, h, sym := parse(t, p)
|
||||
got, err := tb.Add(key, key.src, now, h, sym)
|
||||
require.NoError(t, err)
|
||||
if got != nil {
|
||||
res = got
|
||||
}
|
||||
}
|
||||
require.NotNil(t, res)
|
||||
tb.Answered(key, res, now)
|
||||
}
|
||||
|
||||
// Two paths carry the same message. Each has its own sender here because
|
||||
// the initiator offers the same symbols on every path.
|
||||
direct := testKey{"direct", 1}
|
||||
relayed := testKey{"relay", 1}
|
||||
sd, err := NewSender(msg, testSubtype, 0, 1, 1)
|
||||
require.NoError(t, err)
|
||||
sr, err := NewSender(msg, testSubtype, 0, 1, 1)
|
||||
require.NoError(t, err)
|
||||
answer(direct, sd)
|
||||
answer(relayed, sr)
|
||||
|
||||
// A retry right after the answer carries K fresh symbols, but the clock on
|
||||
// that path has not run out.
|
||||
now = now.Add(10 * time.Millisecond)
|
||||
assert.Zero(t, repeats(direct, attempt(sd)), "a repeat inside the interval is not reported")
|
||||
|
||||
// Once it has, the first fresh symbol of the next retry is enough: the
|
||||
// fresh symbols kept counting.
|
||||
now = now.Add(100 * time.Millisecond)
|
||||
retry := attempt(sd)
|
||||
assert.Equal(t, 1, repeats(direct, retry[:1]), "the held repeat is reported at once")
|
||||
assert.Zero(t, repeats(direct, retry[1:]), "and only once per retry")
|
||||
|
||||
// The other path has its own clock, which only its own answer started.
|
||||
assert.Equal(t, 1, repeats(relayed, attempt(sr)), "a repeat on another path is independent")
|
||||
assert.Zero(t, repeats(relayed, attempt(sr)), "and is itself clocked")
|
||||
|
||||
// Without an interval every K fresh symbols is a repeat, which is what the
|
||||
// other tests rely on.
|
||||
tb = NewTable[testKey, string](testConfig())
|
||||
s2, err := NewSender(msg, testSubtype, 0, 1, 2)
|
||||
require.NoError(t, err)
|
||||
k2 := testKey{"a", 2}
|
||||
answer(k2, s2)
|
||||
assert.Equal(t, 1, repeats(k2, attempt(s2)))
|
||||
assert.Equal(t, 1, repeats(k2, attempt(s2)))
|
||||
}
|
||||
@@ -34,7 +34,8 @@ type Sender struct {
|
||||
}
|
||||
|
||||
// NewSender prepares msg for sending. subtype, remoteIndex and counter fill the
|
||||
// Nebula header of every fragment; fragID is the sender's local index.
|
||||
// Nebula header of every fragment; fragID is the sender's local index. The
|
||||
// Sender keeps msg, which must not change while it is in use.
|
||||
func NewSender(msg []byte, subtype header.MessageSubType, remoteIndex uint32, counter uint64, fragID uint32) (*Sender, error) {
|
||||
if len(msg) == 0 || len(msg) > math.MaxUint16 {
|
||||
return nil, ErrMsgLen
|
||||
@@ -85,8 +86,11 @@ func (s *Sender) Attempt(repair int) (now, later [][]byte, err error) {
|
||||
k := s.enc.Layout().K
|
||||
now = make([][]byte, 0, k)
|
||||
later = make([][]byte, 0, repair)
|
||||
// One allocation backs every packet of the attempt.
|
||||
pktCap := header.Len + HeaderLen + CookieLen + s.enc.Layout().SymbolSize
|
||||
buf := make([]byte, (k+repair)*pktCap)
|
||||
for i := range k + repair {
|
||||
p, err := s.packet(s.next)
|
||||
p, err := s.packet(buf[i*pktCap:i*pktCap:(i+1)*pktCap], s.next)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -100,10 +104,11 @@ func (s *Sender) Attempt(repair int) (now, later [][]byte, err error) {
|
||||
return now, later, nil
|
||||
}
|
||||
|
||||
func (s *Sender) packet(index int) ([]byte, error) {
|
||||
// packet builds the packet for the symbol at index in the capacity of p, which
|
||||
// must have room for it.
|
||||
func (s *Sender) packet(p []byte, index int) ([]byte, error) {
|
||||
l := s.enc.Layout()
|
||||
p := make([]byte, header.Len, header.Len+HeaderLen+CookieLen+l.SymbolSize)
|
||||
header.Encode(p, header.Version, header.Handshake, s.subtype, s.remoteIndex, s.counter)
|
||||
p = header.Encode(p[:header.Len], header.Version, header.Handshake, s.subtype, s.remoteIndex, s.counter)
|
||||
h := Header{
|
||||
FragID: s.fragID,
|
||||
MsgLen: uint16(l.MsgLen),
|
||||
|
||||
+126
-4
@@ -1,10 +1,14 @@
|
||||
package fragment
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/handshake/fec"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -20,6 +24,10 @@ type TableConfig struct {
|
||||
MaxPerSource int // messages in progress per source
|
||||
MaxMsgLen int // largest message accepted
|
||||
TTL time.Duration // an entry idle this long is dropped
|
||||
|
||||
// RepeatInterval is how often, at most, an answered message is reported as a
|
||||
// repeat on one key. Zero reports every K fresh symbols.
|
||||
RepeatInterval time.Duration
|
||||
}
|
||||
|
||||
// Table reassembles messages from senders that have not authenticated yet, the
|
||||
@@ -30,6 +38,15 @@ type TableConfig struct {
|
||||
// K identifies one message, typically the source plus FragID. S identifies the
|
||||
// source for quotas, typically the address masked to /32 or /64.
|
||||
//
|
||||
// A message the caller answered is remembered, see Answered, so the fragments
|
||||
// still arriving for it do not start it over. Without that, the repair
|
||||
// fragments trailing a message whose data fragments already completed it would
|
||||
// open a new entry that, for K above the repair count, never completes: it holds
|
||||
// symbols and a source's quota until it expires. A retry of an answered message
|
||||
// is reported as a repeat, at most once per RepeatInterval on that key. Keys
|
||||
// include the path a message arrives by, so the same message arriving by two
|
||||
// paths is two keys with two clocks.
|
||||
//
|
||||
// A Table is safe for concurrent use.
|
||||
type Table[K, S comparable] struct {
|
||||
mu sync.Mutex
|
||||
@@ -38,6 +55,21 @@ type Table[K, S comparable] struct {
|
||||
order []K
|
||||
perSource map[S]int
|
||||
bytes int
|
||||
answered map[K]*answeredEntry
|
||||
}
|
||||
|
||||
// answeredEntry is what is kept of an answered message: no symbols, only which
|
||||
// indexes have been seen, so a retry's fresh symbols can be told apart from
|
||||
// stragglers of an attempt already decoded.
|
||||
type answeredEntry struct {
|
||||
hash [sha256.Size]byte
|
||||
msgLen uint16
|
||||
k int
|
||||
seen [fec.MaxSymbols]bool
|
||||
fresh int
|
||||
received int
|
||||
lastSeen time.Time
|
||||
lastRepeat time.Time // when it was answered, or last reported as a repeat
|
||||
}
|
||||
|
||||
type tableEntry[K, S comparable] struct {
|
||||
@@ -52,13 +84,25 @@ func NewTable[K, S comparable](cfg TableConfig) *Table[K, S] {
|
||||
cfg: cfg,
|
||||
entries: make(map[K]*tableEntry[K, S]),
|
||||
perSource: make(map[S]int),
|
||||
answered: make(map[K]*answeredEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// Result describes a completed message.
|
||||
type Result struct {
|
||||
Msg []byte // the decoded message
|
||||
Received int // packet bytes received for it, for the amplification budget
|
||||
Msg []byte // the decoded message, nil for a repeat
|
||||
Packet []byte // header.Len bytes for the caller's Nebula header, then Msg
|
||||
Hash [sha256.Size]byte // sha256 of the message
|
||||
Received int // packet bytes received for it, for the amplification budget
|
||||
|
||||
// Repeat means a message marked Answered was sent again: as many fresh
|
||||
// symbols as it has data symbols arrived, which a retry offers and stragglers
|
||||
// of an attempt already decoded do not.
|
||||
Repeat bool
|
||||
|
||||
msgLen uint16
|
||||
k int
|
||||
seen [fec.MaxSymbols]bool
|
||||
}
|
||||
|
||||
// Add records a fragment parsed by Parse. When the message is complete its entry
|
||||
@@ -70,6 +114,15 @@ func (t *Table[K, S]) Add(key K, source S, now time.Time, h Header, sym []byte)
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if a, ok := t.answered[key]; ok {
|
||||
if now.Sub(a.lastSeen) <= t.cfg.TTL {
|
||||
res := a.add(now, h, sym, t.cfg.RepeatInterval)
|
||||
t.mu.Unlock()
|
||||
return res, nil
|
||||
}
|
||||
delete(t.answered, key)
|
||||
}
|
||||
|
||||
e, ok := t.entries[key]
|
||||
if ok && now.Sub(e.lastSeen) > t.cfg.TTL {
|
||||
t.remove(key, e)
|
||||
@@ -107,11 +160,75 @@ func (t *Table[K, S]) Add(key K, source S, now time.Time, h Header, sym []byte)
|
||||
t.remove(key, e)
|
||||
t.mu.Unlock()
|
||||
|
||||
msg, err := e.a.Decode()
|
||||
pkt, err := e.a.Decode(make([]byte, header.Len))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Result{Msg: msg, Received: e.a.Received()}, nil
|
||||
msg := pkt[header.Len:]
|
||||
return &Result{
|
||||
Msg: msg,
|
||||
Packet: pkt,
|
||||
Hash: sha256.Sum256(msg),
|
||||
Received: e.a.Received(),
|
||||
msgLen: e.a.msgLen,
|
||||
k: e.a.dec.Layout().K,
|
||||
seen: e.a.dec.Seen(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *answeredEntry) add(now time.Time, h Header, sym []byte, interval time.Duration) *Result {
|
||||
if h.MsgLen != a.msgLen {
|
||||
return nil
|
||||
}
|
||||
a.lastSeen = now
|
||||
a.received += header.Len + HeaderLen + len(sym)
|
||||
if a.seen[h.Index] {
|
||||
return nil
|
||||
}
|
||||
a.seen[h.Index] = true
|
||||
a.fresh++
|
||||
if a.fresh < a.k || now.Sub(a.lastRepeat) < interval {
|
||||
// Not enough fresh symbols yet, or this key was answered within the
|
||||
// interval. The fresh symbols keep counting, so the first one to arrive
|
||||
// once the interval is up reports the repeat.
|
||||
return nil
|
||||
}
|
||||
r := &Result{Hash: a.hash, Received: a.received, Repeat: true}
|
||||
a.fresh = 0
|
||||
a.received = 0
|
||||
a.lastRepeat = now
|
||||
return r
|
||||
}
|
||||
|
||||
// Answered records that the caller answered res, the result of Add for key, so
|
||||
// later fragments of it are counted rather than reassembled. A message is kept
|
||||
// for the TTL after its last fragment, outside the entry, byte and source caps;
|
||||
// at most MaxEntries are kept.
|
||||
func (t *Table[K, S]) Answered(key K, res *Result, now time.Time) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
// A straggler may have opened an entry while the caller worked.
|
||||
if e, ok := t.entries[key]; ok {
|
||||
t.remove(key, e)
|
||||
}
|
||||
if res.Repeat {
|
||||
return
|
||||
}
|
||||
if _, ok := t.answered[key]; !ok && len(t.answered) >= t.cfg.MaxEntries {
|
||||
for k := range t.answered {
|
||||
delete(t.answered, k)
|
||||
break
|
||||
}
|
||||
}
|
||||
t.answered[key] = &answeredEntry{hash: res.Hash, msgLen: res.msgLen, k: res.k, seen: res.seen, lastSeen: now, lastRepeat: now}
|
||||
}
|
||||
|
||||
// Forget drops what Answered recorded for key, so its fragments are reassembled
|
||||
// again.
|
||||
func (t *Table[K, S]) Forget(key K) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
delete(t.answered, key)
|
||||
}
|
||||
|
||||
// Expire drops every entry idle for longer than the TTL.
|
||||
@@ -128,6 +245,11 @@ func (t *Table[K, S]) Expire(now time.Time) {
|
||||
}
|
||||
i++
|
||||
}
|
||||
for key, a := range t.answered {
|
||||
if now.Sub(a.lastSeen) > t.cfg.TTL {
|
||||
delete(t.answered, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of messages in progress.
|
||||
|
||||
@@ -24,9 +24,9 @@ message NebulaHandshakeDetails {
|
||||
uint64 Cookie = 4 [deprecated = true];
|
||||
uint64 Time = 5;
|
||||
uint32 CertVersion = 8;
|
||||
// KEMKey is the initiator's ephemeral ML-KEM-1024 encapsulation key. It is
|
||||
// only present in msg1 of the ix_psk2_mlkem1024 subtype.
|
||||
bytes KEMKey = 9;
|
||||
// reserved for WIP multiport
|
||||
reserved 6, 7;
|
||||
// 9 carried an ephemeral ML-KEM key in ix_psk2_mlkem1024, a handshake that
|
||||
// was never released
|
||||
reserved 9;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/header"
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"crypto/mlkem"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func hybridCipherSuite(curve cert.Curve) noise.CipherSuite {
|
||||
if curve == cert.Curve_P256 {
|
||||
return noise.NewCipherSuite(noiseutil.DHP256, noise.CipherAESGCM, noise.HashSHA256)
|
||||
}
|
||||
return noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
|
||||
}
|
||||
|
||||
// newHybridCertState builds a peer holding a v3 certificate, with credentials for it and for its v2 form, the way
|
||||
// the pki does.
|
||||
func newHybridCertState(t *testing.T, curve cert.Curve, ca cert.Certificate, caKey []byte, name string, network string) (*testCertState, []byte) {
|
||||
t.Helper()
|
||||
c, _, rawPrivKey, _ := ct.NewTestCert(
|
||||
cert.Version3, curve, ca, caKey,
|
||||
name, ca.NotBefore(), ca.NotAfter(), []netip.Prefix{netip.MustParsePrefix(network)}, nil, nil,
|
||||
)
|
||||
priv, _, _, err := cert.UnmarshalPrivateKeyFromPEM(rawPrivKey)
|
||||
require.NoError(t, err)
|
||||
return hybridCertStateFor(t, curve, c, priv), priv
|
||||
}
|
||||
|
||||
func hybridCertStateFor(t *testing.T, curve cert.Curve, c cert.Certificate, priv []byte) *testCertState {
|
||||
t.Helper()
|
||||
hs3, err := c.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
v2 := cert.V2Form(c)
|
||||
hs2, err := v2.MarshalForHandshakes()
|
||||
require.NoError(t, err)
|
||||
|
||||
ncs := hybridCipherSuite(curve)
|
||||
return &testCertState{
|
||||
version: cert.Version3,
|
||||
creds: map[cert.Version]*Credential{
|
||||
cert.Version3: NewCredential(c, hs3, priv, ncs),
|
||||
cert.Version2: NewCredential(v2, hs2, priv[:len(priv)-cert.MLKEM1024PrivateKeySize], ncs),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newHybridMachine(t *testing.T, cs *testCertState, verifier CertVerifier, initiator bool, localIndex uint32) *Machine {
|
||||
t.Helper()
|
||||
m, err := NewMachine(
|
||||
cert.Version3, cs.getCredential,
|
||||
verifier, func() (uint32, error) { return localIndex, nil },
|
||||
initiator, header.HandshakeIXHybridMLKEM1024,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return m
|
||||
}
|
||||
|
||||
type hybridPeers struct {
|
||||
pool *cert.CAPool
|
||||
ca cert.Certificate
|
||||
caKey []byte
|
||||
initCS, respCS *testCertState
|
||||
initPriv, respPriv []byte
|
||||
}
|
||||
|
||||
func newHybridPeers(t *testing.T, curve cert.Curve) hybridPeers {
|
||||
t.Helper()
|
||||
ca, _, caKey, _ := ct.NewTestCaCert(cert.Version3, curve, time.Now().Add(-time.Hour), time.Now().Add(time.Hour), nil, nil, nil)
|
||||
pool := cert.NewCAPool()
|
||||
require.NoError(t, pool.AddCA(ca))
|
||||
initCS, initPriv := newHybridCertState(t, curve, ca, caKey, "initiator", "10.0.0.1/24")
|
||||
respCS, respPriv := newHybridCertState(t, curve, ca, caKey, "responder", "10.0.0.2/24")
|
||||
return hybridPeers{pool: pool, ca: ca, caKey: caKey, initCS: initCS, respCS: respCS, initPriv: initPriv, respPriv: respPriv}
|
||||
}
|
||||
|
||||
func TestHybridIX(t *testing.T) {
|
||||
for _, curve := range []cert.Curve{cert.Curve_CURVE25519, cert.Curve_P256} {
|
||||
t.Run(curve.String(), func(t *testing.T) {
|
||||
p := newHybridPeers(t, curve)
|
||||
v := testVerifier(p.pool)
|
||||
initM := newHybridMachine(t, p.initCS, v, true, 1000)
|
||||
respM := newHybridMachine(t, p.respCS, v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// The responder answers msg1 but can not complete until msg3.
|
||||
msg2, respResult, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, respResult)
|
||||
require.NotEmpty(t, msg2)
|
||||
|
||||
// The initiator completes by writing msg3.
|
||||
msg3, initResult, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initResult)
|
||||
require.NotEmpty(t, msg3)
|
||||
|
||||
out, respResult, err := respM.ProcessPacket(nil, msg3)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, out)
|
||||
require.NotNil(t, respResult)
|
||||
|
||||
t.Logf("msg1 %d B, msg2 %d B, msg3 %d B", len(msg1), len(msg2), len(msg3))
|
||||
for i, msg := range [][]byte{msg1, msg2, msg3} {
|
||||
h := &header.H{}
|
||||
require.NoError(t, h.Parse(msg))
|
||||
assert.Equal(t, header.HandshakeIXHybridMLKEM1024, h.Subtype)
|
||||
assert.Equal(t, uint64(i+1), h.MessageCounter)
|
||||
}
|
||||
|
||||
assert.Equal(t, uint32(2000), initResult.RemoteIndex)
|
||||
assert.Equal(t, uint32(1000), respResult.RemoteIndex)
|
||||
assert.Equal(t, cert.Version3, initResult.RemoteCert.Certificate.Version())
|
||||
assert.Equal(t, cert.Version3, respResult.RemoteCert.Certificate.Version())
|
||||
assert.Equal(t, "responder", initResult.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, "initiator", respResult.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, cert.Version3, initResult.MyCert.Version())
|
||||
assert.Equal(t, uint64(3), initResult.MessageIndex)
|
||||
assert.Equal(t, uint64(3), respResult.MessageIndex)
|
||||
|
||||
// The keys pair up in both directions.
|
||||
for _, pair := range [][2]*Result{{initResult, respResult}, {respResult, initResult}} {
|
||||
ct, err := pair[0].EKey.Encrypt(nil, nil, []byte("hello"))
|
||||
require.NoError(t, err)
|
||||
pt, err := pair[1].DKey.Decrypt(nil, nil, ct)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("hello"), pt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A hybrid handshake needs v3 certificates, and a v3 certificate needs a hybrid handshake.
|
||||
func TestHybridIX_CertVersions(t *testing.T) {
|
||||
p := newHybridPeers(t, cert.Curve_CURVE25519)
|
||||
v := testVerifier(p.pool)
|
||||
|
||||
_, err := NewMachine(cert.Version2, p.initCS.getCredential, v, func() (uint32, error) { return 1, nil }, true, header.HandshakeIXHybridMLKEM1024)
|
||||
require.ErrorIs(t, err, ErrCertVersionMismatch)
|
||||
_, err = NewMachine(cert.Version3, p.initCS.getCredential, v, func() (uint32, error) { return 1, nil }, true, header.HandshakeIXPSK0)
|
||||
require.ErrorIs(t, err, ErrCertVersionMismatch)
|
||||
|
||||
// The v2 form still does a classical handshake, here with a peer that only has v2.
|
||||
ca2 := cert.V2Form(p.ca)
|
||||
pool2 := cert.NewCAPool()
|
||||
require.NoError(t, pool2.AddCA(ca2))
|
||||
classicalCAKey := p.caKey[:len(p.caKey)-cert.MLDSA87PrivateKeySize]
|
||||
v2Peer := newTestCertState(t, ca2, classicalCAKey, "v2peer", []netip.Prefix{netip.MustParsePrefix("10.0.0.3/24")})
|
||||
p.initCS.version = cert.Version2
|
||||
initResult, respResult := doFullHandshake(t, p.initCS, v2Peer, pool2)
|
||||
assert.Equal(t, cert.Version2, initResult.RemoteCert.Certificate.Version())
|
||||
assert.Equal(t, cert.Version2, respResult.RemoteCert.Certificate.Version())
|
||||
assert.Equal(t, cert.Version2, initResult.MyCert.Version())
|
||||
}
|
||||
|
||||
// A responder that only trusts the v2 form of the CA can not verify a v3 certificate.
|
||||
func TestHybridIX_V2TrustOnly(t *testing.T) {
|
||||
p := newHybridPeers(t, cert.Curve_CURVE25519)
|
||||
pool2 := cert.NewCAPool()
|
||||
require.NoError(t, pool2.AddCA(cert.V2Form(p.ca)))
|
||||
|
||||
initM := newHybridMachine(t, p.initCS, testVerifier(p.pool), true, 1000)
|
||||
respM := newHybridMachine(t, p.respCS, testVerifier(pool2), false, 2000)
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
_, _, err = respM.ProcessPacket(nil, msg1)
|
||||
require.ErrorIs(t, err, cert.ErrCaNotFound)
|
||||
}
|
||||
|
||||
// A corrupted msg3 is dropped without killing the responder, and the real one still completes.
|
||||
func TestHybridIX_CorruptMsg3(t *testing.T) {
|
||||
p := newHybridPeers(t, cert.Curve_CURVE25519)
|
||||
v := testVerifier(p.pool)
|
||||
initM := newHybridMachine(t, p.initCS, v, true, 1000)
|
||||
respM := newHybridMachine(t, p.respCS, v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, _, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
msg3, _, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
|
||||
bad := append([]byte(nil), msg3...)
|
||||
bad[header.Len+10] ^= 1
|
||||
_, res, err := respM.ProcessPacket(nil, bad)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, res)
|
||||
require.False(t, respM.Failed())
|
||||
|
||||
_, res, err = respM.ProcessPacket(nil, msg3)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res)
|
||||
}
|
||||
|
||||
// withKEMKey returns a peer holding c and its classical private key, but some other ML-KEM key: someone who broke
|
||||
// the classical key, say with a quantum computer, and wants to be that peer.
|
||||
func withKEMKey(t *testing.T, curve cert.Curve, c cert.Certificate, priv []byte) *testCertState {
|
||||
t.Helper()
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
forged := append(append([]byte(nil), priv[:len(priv)-cert.MLKEM1024PrivateKeySize]...), dk.Bytes()...)
|
||||
return hybridCertStateFor(t, curve, c, forged)
|
||||
}
|
||||
|
||||
// The classical private key alone does not get anyone through as the initiator: msg2 is unreadable without the
|
||||
// initiator's ML-KEM key.
|
||||
func TestHybridIX_ImpersonateInitiator(t *testing.T) {
|
||||
p := newHybridPeers(t, cert.Curve_CURVE25519)
|
||||
v := testVerifier(p.pool)
|
||||
victim := p.initCS.creds[cert.Version3].Cert
|
||||
attacker := withKEMKey(t, cert.Curve_CURVE25519, victim, p.initPriv)
|
||||
|
||||
initM := newHybridMachine(t, attacker, v, true, 1000)
|
||||
respM := newHybridMachine(t, p.respCS, v, false, 2000)
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, _, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, res, err := initM.ProcessPacket(nil, msg2)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, res)
|
||||
}
|
||||
|
||||
// The classical private key alone does not get anyone through as the responder either: the initiator completes,
|
||||
// but msg3 is unreadable without the responder's ML-KEM key, so no packet under the new keys can ever come back.
|
||||
func TestHybridIX_ImpersonateResponder(t *testing.T) {
|
||||
p := newHybridPeers(t, cert.Curve_CURVE25519)
|
||||
v := testVerifier(p.pool)
|
||||
victim := p.respCS.creds[cert.Version3].Cert
|
||||
attacker := withKEMKey(t, cert.Curve_CURVE25519, victim, p.respPriv)
|
||||
|
||||
initM := newHybridMachine(t, p.initCS, v, true, 1000)
|
||||
respM := newHybridMachine(t, attacker, v, false, 2000)
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, _, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
msg3, initResult, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initResult)
|
||||
|
||||
_, res, err := respM.ProcessPacket(nil, msg3)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, res)
|
||||
}
|
||||
+61
-49
@@ -1,68 +1,80 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"crypto/hkdf"
|
||||
"crypto/mlkem"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
"io"
|
||||
|
||||
// kemPSKSalt separates the psk derivation from any other use of the secret.
|
||||
const kemPSKSalt = "nebula ix_psk2_mlkem1024 v1"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
var ErrInvalidKEMKey = errors.New("peer sent an invalid ML-KEM encapsulation key")
|
||||
|
||||
// kemPSK derives the noise psk from an ML-KEM shared secret. The ciphertext is
|
||||
// bound in because, unlike the encapsulation key, it travels outside the noise
|
||||
// transcript.
|
||||
func kemPSK(sharedKey, ciphertext []byte) ([]byte, error) {
|
||||
secret := make([]byte, 0, len(sharedKey)+len(ciphertext))
|
||||
secret = append(secret, sharedKey...)
|
||||
secret = append(secret, ciphertext...)
|
||||
return hkdf.Extract(sha256.New, secret, []byte(kemPSKSalt))
|
||||
// KEMMLKEM1024 is ML-KEM-1024 for the noise library's hybrid patterns. Private
|
||||
// keys are the 64 byte seed, the same form v3 private keys store.
|
||||
var KEMMLKEM1024 noise.KEMFunc = kemMLKEM1024{}
|
||||
|
||||
type kemMLKEM1024 struct{}
|
||||
|
||||
// GenerateKeypair ignores random, crypto/mlkem always draws from crypto/rand.
|
||||
func (kemMLKEM1024) GenerateKeypair(_ io.Reader) (noise.KEMKey, error) {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
if err != nil {
|
||||
return noise.KEMKey{}, fmt.Errorf("mlkem1024: GenerateKey: %w", err)
|
||||
}
|
||||
return noise.KEMKey{Private: dk.Bytes(), Public: dk.EncapsulationKey().Bytes()}, nil
|
||||
}
|
||||
|
||||
// kemEncapsulate is the responder half: encapsulate to the initiator's key,
|
||||
// install the psk, and remember the ciphertext to prefix the response with.
|
||||
func (m *Machine) kemEncapsulate(encapsulationKey []byte) error {
|
||||
ek, err := mlkem.NewEncapsulationKey1024(encapsulationKey)
|
||||
func (kemMLKEM1024) Encapsulate(pubkey []byte) ([]byte, []byte, error) {
|
||||
ek, err := mlkem.NewEncapsulationKey1024(pubkey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalidKEMKey, err)
|
||||
return nil, nil, fmt.Errorf("%w: %w", ErrInvalidKEMKey, err)
|
||||
}
|
||||
sharedKey, ct := ek.Encapsulate()
|
||||
psk, err := kemPSK(sharedKey, ct)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.hs.SetPresharedKey(psk); err != nil {
|
||||
return err
|
||||
}
|
||||
m.kemCiphertext = ct
|
||||
return nil
|
||||
ss, ct := ek.Encapsulate()
|
||||
return ct, ss, nil
|
||||
}
|
||||
|
||||
// kemDecapsulate is the initiator half: recover the shared secret from the
|
||||
// ciphertext prefixing the response and install the psk. It returns the rest of
|
||||
// the message, which is the noise message.
|
||||
func (m *Machine) kemDecapsulate(msg []byte) ([]byte, error) {
|
||||
if len(msg) < mlkem.CiphertextSize1024 {
|
||||
return nil, ErrPacketTooShort
|
||||
}
|
||||
if m.kemKey == nil {
|
||||
return nil, errors.New("no ML-KEM decapsulation key for this handshake")
|
||||
}
|
||||
ct := msg[:mlkem.CiphertextSize1024]
|
||||
sharedKey, err := m.kemKey.Decapsulate(ct)
|
||||
func (kemMLKEM1024) Decapsulate(privkey, ciphertext []byte) ([]byte, error) {
|
||||
dk, err := mlkem.NewDecapsulationKey1024(privkey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("mlkem1024: NewDecapsulationKey: %w", err)
|
||||
}
|
||||
psk, err := kemPSK(sharedKey, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := m.hs.SetPresharedKey(psk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg[mlkem.CiphertextSize1024:], nil
|
||||
return dk.Decapsulate(ciphertext)
|
||||
}
|
||||
|
||||
// mlkem1024Keys is KEMMLKEM1024 for one handshake. It decapsulates with the
|
||||
// keys it holds expanded, the static one from the Credential and the ephemeral
|
||||
// one it generated, rather than expanding them again from the seeds noise hands
|
||||
// back; any other private key is expanded as usual.
|
||||
type mlkem1024Keys struct {
|
||||
kemMLKEM1024
|
||||
static *mlkem.DecapsulationKey1024
|
||||
staticSeed []byte
|
||||
ephemeral *mlkem.DecapsulationKey1024
|
||||
ephemeralSeed []byte
|
||||
}
|
||||
|
||||
func (k *mlkem1024Keys) GenerateKeypair(_ io.Reader) (noise.KEMKey, error) {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
if err != nil {
|
||||
return noise.KEMKey{}, fmt.Errorf("mlkem1024: GenerateKey: %w", err)
|
||||
}
|
||||
k.ephemeral, k.ephemeralSeed = dk, dk.Bytes()
|
||||
return noise.KEMKey{Private: k.ephemeralSeed, Public: dk.EncapsulationKey().Bytes()}, nil
|
||||
}
|
||||
|
||||
func (k *mlkem1024Keys) Decapsulate(privkey, ciphertext []byte) ([]byte, error) {
|
||||
switch {
|
||||
case k.static != nil && subtle.ConstantTimeCompare(privkey, k.staticSeed) == 1:
|
||||
return k.static.Decapsulate(ciphertext)
|
||||
case k.ephemeral != nil && subtle.ConstantTimeCompare(privkey, k.ephemeralSeed) == 1:
|
||||
return k.ephemeral.Decapsulate(ciphertext)
|
||||
}
|
||||
return k.kemMLKEM1024.Decapsulate(privkey, ciphertext)
|
||||
}
|
||||
|
||||
func (kemMLKEM1024) PublicKeyLen() int { return mlkem.EncapsulationKeySize1024 }
|
||||
func (kemMLKEM1024) CiphertextLen() int { return mlkem.CiphertextSize1024 }
|
||||
func (kemMLKEM1024) KEMName() string { return "MLKEM1024" }
|
||||
@@ -1,208 +0,0 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mlkem"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newKEMMachine(t *testing.T, cs *testCertState, v CertVerifier, initiator bool, index uint32) *Machine {
|
||||
t.Helper()
|
||||
m, err := NewMachine(
|
||||
cs.version, cs.getCredential, v,
|
||||
func() (uint32, error) { return index, nil },
|
||||
initiator, header.HandshakeIXPSK2MLKEM1024,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return m
|
||||
}
|
||||
|
||||
type kemFixture struct {
|
||||
initCS, respCS *testCertState
|
||||
v CertVerifier
|
||||
}
|
||||
|
||||
func newKEMFixture(t *testing.T, cipher noise.CipherFunc) kemFixture {
|
||||
ca, _, caKey, _ := ct.NewTestCaCert(
|
||||
cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil,
|
||||
)
|
||||
return kemFixture{
|
||||
initCS: newTestCertStateWithCipher(t, ca, caKey, "initiator", []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}, cipher),
|
||||
respCS: newTestCertStateWithCipher(t, ca, caKey, "responder", []netip.Prefix{netip.MustParsePrefix("10.0.0.2/24")}, cipher),
|
||||
v: testVerifier(ct.NewTestCAPool(ca)),
|
||||
}
|
||||
}
|
||||
|
||||
func requireKeysMatch(t *testing.T, a, b *Result) {
|
||||
t.Helper()
|
||||
c, err := a.EKey.Encrypt(nil, nil, []byte("hello"))
|
||||
require.NoError(t, err)
|
||||
p, err := b.DKey.Decrypt(nil, nil, c)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("hello"), p)
|
||||
|
||||
c, err = b.EKey.Encrypt(nil, nil, []byte("world"))
|
||||
require.NoError(t, err)
|
||||
p, err = a.DKey.Decrypt(nil, nil, c)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []byte("world"), p)
|
||||
}
|
||||
|
||||
func TestKEMHandshake(t *testing.T) {
|
||||
for _, cipher := range []noise.CipherFunc{noise.CipherChaChaPoly, noise.CipherAESGCM} {
|
||||
t.Run(cipher.CipherName(), func(t *testing.T) {
|
||||
f := newKEMFixture(t, cipher)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, header.HandshakeIXPSK2MLKEM1024, header.MessageSubType(msg1[1]))
|
||||
assert.Greater(t, len(msg1), header.Len+mlkem.EncapsulationKeySize1024)
|
||||
|
||||
msg2, respR, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, respR)
|
||||
assert.Greater(t, len(msg2), header.Len+mlkem.CiphertextSize1024)
|
||||
|
||||
_, initR, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initR)
|
||||
|
||||
assert.Equal(t, "responder", initR.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, "initiator", respR.RemoteCert.Certificate.Name())
|
||||
assert.Equal(t, uint32(2000), initR.RemoteIndex)
|
||||
assert.Equal(t, uint32(1000), respR.RemoteIndex)
|
||||
requireKeysMatch(t, initR, respR)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestKEMSecretMatters checks the ML-KEM secret really reaches the transport
|
||||
// keys: an initiator holding a different decapsulation key cannot complete even
|
||||
// though every DH input is genuine.
|
||||
func TestKEMSecretMatters(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, _, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
|
||||
other, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
initM.kemKey = other
|
||||
|
||||
_, res, err := initM.ProcessPacket(nil, msg2)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, res)
|
||||
}
|
||||
|
||||
func TestKEMTamperedCiphertext(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
msg2, respR, err := respM.ProcessPacket(nil, msg1)
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("truncated", func(t *testing.T) {
|
||||
_, res, err := initM.ProcessPacket(nil, msg2[:header.Len+mlkem.CiphertextSize1024-1])
|
||||
require.ErrorIs(t, err, ErrPacketTooShort)
|
||||
assert.Nil(t, res)
|
||||
assert.False(t, initM.Failed())
|
||||
})
|
||||
|
||||
t.Run("flipped ciphertext bit", func(t *testing.T) {
|
||||
bad := bytes.Clone(msg2)
|
||||
bad[header.Len+10] ^= 1
|
||||
_, res, err := initM.ProcessPacket(nil, bad)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, res)
|
||||
assert.False(t, initM.Failed(), "a forged ciphertext must not kill the handshake")
|
||||
})
|
||||
|
||||
t.Run("genuine response still completes", func(t *testing.T) {
|
||||
_, initR, err := initM.ProcessPacket(nil, msg2)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, initR)
|
||||
requireKeysMatch(t, initR, respR)
|
||||
})
|
||||
}
|
||||
|
||||
// TestKEMBadMsg1 drives processPayload by hand. With the psk modifier msg1's
|
||||
// payload is encrypted under a key derived from the public ephemeral, so a
|
||||
// forged payload would need re-encrypting; the parsing rules are what matter.
|
||||
func TestKEMBadMsg1(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
msg1Flags := subtypeInfos[header.HandshakeIXPSK2MLKEM1024].msgs[0]
|
||||
cert := f.initCS.creds[cert.Version2]
|
||||
payload := func(kemKey []byte) []byte {
|
||||
return MarshalPayload(nil, Payload{
|
||||
Cert: cert.Bytes,
|
||||
CertVersion: uint32(cert.Cert.Version()),
|
||||
InitiatorIndex: 1000,
|
||||
Time: 1,
|
||||
KEMKey: kemKey,
|
||||
})
|
||||
}
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("missing KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
err := m.processPayload(payload(nil), msg1Flags)
|
||||
require.ErrorIs(t, err, ErrUnexpectedContent)
|
||||
assert.True(t, m.Failed())
|
||||
})
|
||||
|
||||
t.Run("invalid KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
// Coefficients of 0xfff exceed the modulus, which ML-KEM must reject.
|
||||
bad := bytes.Repeat([]byte{0xff}, mlkem.EncapsulationKeySize1024)
|
||||
err := m.kemEncapsulate(bad)
|
||||
require.ErrorIs(t, err, ErrInvalidKEMKey)
|
||||
err = m.kemEncapsulate(bad[:100])
|
||||
require.ErrorIs(t, err, ErrInvalidKEMKey)
|
||||
})
|
||||
|
||||
t.Run("valid KEM key", func(t *testing.T) {
|
||||
m := newKEMMachine(t, f.respCS, f.v, false, 2000)
|
||||
require.NoError(t, m.kemEncapsulate(dk.EncapsulationKey().Bytes()))
|
||||
assert.Len(t, m.kemCiphertext, mlkem.CiphertextSize1024)
|
||||
})
|
||||
|
||||
t.Run("KEM key on the classical subtype", func(t *testing.T) {
|
||||
m := newTestMachine(t, f.respCS, f.v, false, 2000)
|
||||
classical := subtypeInfos[header.HandshakeIXPSK0].msgs[0]
|
||||
err := m.processPayload(payload(dk.EncapsulationKey().Bytes()), classical)
|
||||
require.ErrorIs(t, err, ErrUnexpectedContent)
|
||||
assert.True(t, m.Failed())
|
||||
})
|
||||
}
|
||||
|
||||
// TestKEMDistinctFromClassical makes sure the two subtypes cannot be mixed: a
|
||||
// classical responder cannot answer a KEM initiator.
|
||||
func TestKEMDistinctFromClassical(t *testing.T) {
|
||||
f := newKEMFixture(t, noise.CipherChaChaPoly)
|
||||
initM := newKEMMachine(t, f.initCS, f.v, true, 1000)
|
||||
respM := newTestMachine(t, f.respCS, f.v, false, 2000)
|
||||
|
||||
msg1, err := initM.Initiate(nil)
|
||||
require.NoError(t, err)
|
||||
_, _, err = respM.ProcessPacket(nil, msg1)
|
||||
require.ErrorIs(t, err, ErrSubtypeMismatch)
|
||||
}
|
||||
+67
-69
@@ -2,13 +2,11 @@ package handshake
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/mlkem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
@@ -65,13 +63,11 @@ type Machine struct {
|
||||
msgs []msgFlags
|
||||
myVersion cert.Version
|
||||
subtype header.MessageSubType
|
||||
hybrid bool
|
||||
indexAllocated bool
|
||||
remoteCertSet bool
|
||||
payloadSet bool
|
||||
failed bool
|
||||
|
||||
kemKey *mlkem.DecapsulationKey1024 // initiator's ephemeral ML-KEM key, until completion
|
||||
kemCiphertext []byte // responder's ciphertext to prefix its response with
|
||||
}
|
||||
|
||||
// NewMachine creates a handshake state machine. The subtype determines both
|
||||
@@ -91,12 +87,24 @@ func NewMachine(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Version 3 certificates go with hybrid patterns and nothing else, the
|
||||
// classical subtype uses the v2 form instead.
|
||||
hybrid := info.kem != nil
|
||||
if hybrid != (version == cert.Version3) {
|
||||
return nil, fmt.Errorf("%w: %v", ErrCertVersionMismatch, version)
|
||||
}
|
||||
|
||||
cred := getCred(version)
|
||||
if cred == nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrNoCredential, version)
|
||||
}
|
||||
if hybrid {
|
||||
if err := checkHybridSuite(subtype, cred.Cert); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
hs, err := cred.buildHandshakeState(initiator, info.pattern, info.pskPlacement)
|
||||
hs, err := cred.buildHandshakeState(initiator, info)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build noise state: %w", err)
|
||||
}
|
||||
@@ -105,6 +113,7 @@ func NewMachine(
|
||||
hs: hs,
|
||||
subtype: subtype,
|
||||
msgs: info.msgs,
|
||||
hybrid: hybrid,
|
||||
getCred: getCred,
|
||||
allocIndex: allocIndex,
|
||||
verifier: verifier,
|
||||
@@ -126,6 +135,12 @@ func (m *Machine) Subtype() header.MessageSubType {
|
||||
return m.subtype
|
||||
}
|
||||
|
||||
// PeerCert returns the peer's verified certificate once a message carrying it
|
||||
// has been read, which for a three message pattern is before completion.
|
||||
func (m *Machine) PeerCert() *cert.CachedCertificate {
|
||||
return m.result.RemoteCert
|
||||
}
|
||||
|
||||
// MessageIndex returns the noise handshake message index, which equals the
|
||||
// wire counter of the most recently sent or received message.
|
||||
func (m *Machine) MessageIndex() int {
|
||||
@@ -226,23 +241,8 @@ func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) {
|
||||
return nil, nil, ErrInitiateNotCalled
|
||||
}
|
||||
|
||||
// The (eKey, dKey) ordering here is correct for IX, where the initiator
|
||||
// completes the handshake by reading the responder's stage-2 message.
|
||||
// noise returns (cs1, cs2) where cs1 is the initiator->responder cipher.
|
||||
// For 3-message patterns where a responder finishes by reading the final
|
||||
// message, this ordering would be wrong; revisit when XX/pqIX lands.
|
||||
noiseMsg := packet[header.Len:]
|
||||
if m.myMsgFlags().kemCiphertext {
|
||||
var err error
|
||||
// Installing a psk derived from a forged ciphertext is harmless: ReadMessage
|
||||
// then fails without advancing, and the next packet installs its own.
|
||||
noiseMsg, err = m.kemDecapsulate(noiseMsg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
msg, eKey, dKey, err := m.hs.ReadMessage(nil, noiseMsg)
|
||||
msg, cs1, cs2, err := m.hs.ReadMessage(nil, packet[header.Len:])
|
||||
eKey, dKey := m.cipherStates(cs1, cs2)
|
||||
if err != nil {
|
||||
// Noise ReadMessage failed. The noise library checkpoints and rolls back
|
||||
// on failure, so the Machine is still alive. The caller can retry with
|
||||
@@ -272,7 +272,7 @@ func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) {
|
||||
}
|
||||
|
||||
// ReadMessage didn't complete, produce the next outgoing message
|
||||
out, dk, ek, err := m.buildResponse(out)
|
||||
out, ek, dk, err := m.buildResponse(out)
|
||||
if err != nil {
|
||||
m.failed = true
|
||||
return nil, nil, err
|
||||
@@ -292,9 +292,16 @@ func (m *Machine) ProcessPacket(out, packet []byte) ([]byte, *Result, error) {
|
||||
return out, nil, nil
|
||||
}
|
||||
|
||||
// cipherStates orders the cipher states noise returns, (cs1, cs2) with cs1 the
|
||||
// initiator to responder direction, into this side's (eKey, dKey).
|
||||
func (m *Machine) cipherStates(cs1, cs2 *noise.CipherState) (*noise.CipherState, *noise.CipherState) {
|
||||
if m.result.Initiator {
|
||||
return cs1, cs2
|
||||
}
|
||||
return cs2, cs1
|
||||
}
|
||||
|
||||
func (m *Machine) completed(eKey, dKey *noise.CipherState) *Result {
|
||||
m.kemKey = nil
|
||||
m.kemCiphertext = nil
|
||||
m.result.EKey = eKey
|
||||
m.result.DKey = dKey
|
||||
m.result.MessageIndex = uint64(m.hs.MessageIndex())
|
||||
@@ -303,7 +310,7 @@ func (m *Machine) completed(eKey, dKey *noise.CipherState) *Result {
|
||||
|
||||
func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
if len(msg) == 0 {
|
||||
if flags.expectsPayload || flags.expectsCert || flags.kemKey {
|
||||
if flags.expectsPayload || flags.expectsCert {
|
||||
m.failed = true
|
||||
return ErrMissingContent
|
||||
}
|
||||
@@ -329,12 +336,6 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
return ErrUnexpectedContent
|
||||
}
|
||||
|
||||
hasKEMKey := len(payload.KEMKey) > 0
|
||||
if hasKEMKey != flags.kemKey {
|
||||
m.failed = true
|
||||
return ErrUnexpectedContent
|
||||
}
|
||||
|
||||
// Process payload
|
||||
if flags.expectsPayload {
|
||||
var remoteIndex uint32
|
||||
@@ -361,26 +362,39 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
}
|
||||
}
|
||||
|
||||
if flags.kemKey {
|
||||
if err := m.kemEncapsulate(payload.KEMKey); err != nil {
|
||||
m.failed = true
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkHybridSuite checks that a version 3 certificate's suite uses the KEM of
|
||||
// the hybrid subtype.
|
||||
func checkHybridSuite(subtype header.MessageSubType, c cert.Certificate) error {
|
||||
suite := cert.PQSuiteOf(c)
|
||||
if st, ok := HybridSubtype(suite); !ok || st != subtype {
|
||||
return fmt.Errorf("%w: %v", ErrPQSuiteMismatch, suite)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Machine) validateCert(payload Payload) error {
|
||||
// A v3 certificate only ever comes with a hybrid pattern, and a hybrid
|
||||
// pattern only ever with one. The composite static key would not recombine
|
||||
// with anything else anyway, but say so plainly.
|
||||
if m.hybrid != (cert.Version(payload.CertVersion) == cert.Version3) {
|
||||
m.failed = true
|
||||
return fmt.Errorf("%w: %v", ErrCertVersionMismatch, payload.CertVersion)
|
||||
}
|
||||
|
||||
cred := m.getCred(m.myVersion)
|
||||
if cred == nil {
|
||||
m.failed = true
|
||||
return fmt.Errorf("%w: %v", ErrNoCredential, m.myVersion)
|
||||
}
|
||||
// PeerStatic builds a fresh composite key on every call for hybrid patterns.
|
||||
peerStatic := m.hs.PeerStatic()
|
||||
rc, err := cert.Recombine(
|
||||
cert.Version(payload.CertVersion),
|
||||
payload.Cert,
|
||||
m.hs.PeerStatic(),
|
||||
peerStatic,
|
||||
cred.Cert.Curve(),
|
||||
)
|
||||
if err != nil {
|
||||
@@ -388,11 +402,18 @@ func (m *Machine) validateCert(payload Payload) error {
|
||||
return fmt.Errorf("recombine cert: %w", err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(rc.PublicKey(), m.hs.PeerStatic()) {
|
||||
if !bytes.Equal(rc.PublicKey(), peerStatic) {
|
||||
m.failed = true
|
||||
return ErrPublicKeyMismatch
|
||||
}
|
||||
|
||||
if m.hybrid {
|
||||
if err := checkHybridSuite(m.subtype, rc); err != nil {
|
||||
m.failed = true
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Version negotiation, if the peer sent a different version and we have it, switch
|
||||
if rc.Version() != m.myVersion {
|
||||
if m.getCred(rc.Version()) != nil {
|
||||
@@ -412,21 +433,11 @@ func (m *Machine) validateCert(payload Payload) error {
|
||||
}
|
||||
|
||||
func (m *Machine) marshalOutgoing(flags msgFlags) ([]byte, error) {
|
||||
if !flags.expectsPayload && !flags.expectsCert && !flags.kemKey {
|
||||
if !flags.expectsPayload && !flags.expectsCert {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var p Payload
|
||||
if flags.kemKey {
|
||||
if m.kemKey == nil {
|
||||
dk, err := mlkem.GenerateKey1024()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generate ML-KEM key: %w", err)
|
||||
}
|
||||
m.kemKey = dk
|
||||
}
|
||||
p.KEMKey = m.kemKey.EncapsulationKey().Bytes()
|
||||
}
|
||||
if flags.expectsPayload {
|
||||
if !m.indexAllocated {
|
||||
index, err := m.allocIndex()
|
||||
@@ -478,26 +489,13 @@ func (m *Machine) buildResponse(out []byte) ([]byte, *noise.CipherState, *noise.
|
||||
uint64(m.hs.MessageIndex()+1),
|
||||
)
|
||||
|
||||
if flags.kemCiphertext {
|
||||
if m.kemCiphertext == nil {
|
||||
return nil, nil, nil, errors.New("no ML-KEM ciphertext to send")
|
||||
}
|
||||
out = append(out, m.kemCiphertext...)
|
||||
}
|
||||
|
||||
// noise.WriteMessage appends the encrypted handshake message to out,
|
||||
// reusing capacity when present.
|
||||
//
|
||||
// The (dKey, eKey) ordering here is correct for IX, where the responder
|
||||
// completes the handshake by writing the stage-2 message. noise returns
|
||||
// (cs1, cs2) where cs1 is the initiator->responder cipher (which is the
|
||||
// responder's decrypt key). For 3-message patterns where an initiator
|
||||
// finishes by writing the final message, this ordering would be wrong;
|
||||
// revisit when XX/pqIX lands.
|
||||
out, dKey, eKey, err := m.hs.WriteMessage(out, hsBytes)
|
||||
out, cs1, cs2, err := m.hs.WriteMessage(out, hsBytes)
|
||||
if err != nil {
|
||||
return nil, nil, nil, fmt.Errorf("noise WriteMessage: %w", err)
|
||||
}
|
||||
|
||||
return out, dKey, eKey, nil
|
||||
eKey, dKey := m.cipherStates(cs1, cs2)
|
||||
return out, eKey, dKey, nil
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/header"
|
||||
|
||||
+46
-18
@@ -3,7 +3,8 @@ package handshake
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
@@ -11,16 +12,18 @@ import (
|
||||
type msgFlags struct {
|
||||
expectsPayload bool // message carries indexes and time
|
||||
expectsCert bool // message carries the certificate
|
||||
kemKey bool // payload carries an ML-KEM encapsulation key
|
||||
kemCiphertext bool // message is prefixed with the ML-KEM ciphertext for the peer's key
|
||||
}
|
||||
|
||||
// subtypeInfo bundles the noise pattern with the per-message flags for a
|
||||
// given handshake subtype.
|
||||
type subtypeInfo struct {
|
||||
pattern noise.HandshakePattern
|
||||
pskPlacement int // noise psk modifier position, 0 means no psk token
|
||||
msgs []msgFlags
|
||||
pattern noise.HandshakePattern
|
||||
msgs []msgFlags
|
||||
|
||||
// kem is the KEM of a hybrid pattern, nil for any other. Hybrid patterns
|
||||
// carry composite static keys and need version 3 certificates on both
|
||||
// sides, in suites using this KEM; every other pattern refuses them.
|
||||
kem noise.KEMFunc
|
||||
}
|
||||
|
||||
// subtypeInfos defines the noise pattern and message content layout for each
|
||||
@@ -35,19 +38,24 @@ var subtypeInfos = map[header.MessageSubType]subtypeInfo{
|
||||
},
|
||||
},
|
||||
|
||||
// IX with an ephemeral ML-KEM-1024 exchange:
|
||||
// msg1 (I->R): payload + cert + encapsulation key
|
||||
// msg2 (R->I): ciphertext || noise(payload + cert)
|
||||
// The responder encapsulates after reading msg1 and mixes the shared secret in
|
||||
// through the psk2 token at the end of msg2. The ciphertext travels outside the
|
||||
// noise message because the initiator needs the secret before it can process
|
||||
// that token.
|
||||
header.HandshakeIXPSK2MLKEM1024: {
|
||||
pattern: noise.HandshakeIX,
|
||||
pskPlacement: 2,
|
||||
// Hybrid IX (github.com/DefinedNet/noise, see its PQ_RESEARCH.md):
|
||||
// msg1 (I->R): e, s payload + cert
|
||||
// msg2 (R->I): ekem, skem, e, ee, se, s, es payload + cert
|
||||
// msg3 (I->R): skem
|
||||
// e and s are composite, classical || ML-KEM-1024, except the responder's e:
|
||||
// it follows the responder's ekem, which already completed the ephemeral KEM
|
||||
// exchange, so it carries only the classical key. The static ML-KEM key is
|
||||
// the post-quantum half of the v3 certificate's public key, so it travels in
|
||||
// s and the certificate leaves it out. The responder authenticates the
|
||||
// initiator when msg3 decrypts, and the initiator the responder when the
|
||||
// first packet under the new keys does.
|
||||
header.HandshakeIXHybridMLKEM1024: {
|
||||
pattern: noise.HandshakeHybridIX,
|
||||
kem: KEMMLKEM1024,
|
||||
msgs: []msgFlags{
|
||||
{expectsPayload: true, expectsCert: true, kemKey: true},
|
||||
{expectsPayload: true, expectsCert: true, kemCiphertext: true},
|
||||
{expectsPayload: true, expectsCert: true},
|
||||
{expectsPayload: true, expectsCert: true},
|
||||
{},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -65,6 +73,26 @@ var subtypeInfos = map[header.MessageSubType]subtypeInfo{
|
||||
//},
|
||||
}
|
||||
|
||||
// hybridSubtypes maps the suite of a version 3 certificate to the hybrid
|
||||
// subtype for its KEM. Peers need the same KEM, not the same suite, so suites
|
||||
// sharing a KEM share a subtype; the suite itself travels in the certificate.
|
||||
var hybridSubtypes = map[cert.PQSuite]header.MessageSubType{
|
||||
cert.PQSuite_MLKEM1024_MLDSA87: header.HandshakeIXHybridMLKEM1024,
|
||||
}
|
||||
|
||||
// HybridSubtype returns the hybrid handshake subtype for the KEM of a version 3
|
||||
// certificate's suite.
|
||||
func HybridSubtype(suite cert.PQSuite) (header.MessageSubType, bool) {
|
||||
st, ok := hybridSubtypes[suite]
|
||||
return st, ok
|
||||
}
|
||||
|
||||
// IsHybrid reports whether subtype is a hybrid handshake, one that needs version
|
||||
// 3 certificates.
|
||||
func IsHybrid(subtype header.MessageSubType) bool {
|
||||
return subtypeInfos[subtype].kem != nil
|
||||
}
|
||||
|
||||
func subtypeInfoFor(subtype header.MessageSubType) (subtypeInfo, error) {
|
||||
if info, ok := subtypeInfos[subtype]; ok {
|
||||
return info, nil
|
||||
|
||||
@@ -3,7 +3,7 @@ package handshake
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
+28
-35
@@ -1,8 +1,10 @@
|
||||
package handshake
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math"
|
||||
"slices"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protowire"
|
||||
)
|
||||
@@ -20,7 +22,6 @@ type Payload struct {
|
||||
ResponderIndex uint32
|
||||
Time uint64
|
||||
CertVersion uint32
|
||||
KEMKey []byte // ML-KEM encapsulation key, only in subtypes that carry one
|
||||
}
|
||||
|
||||
// Proto field numbers for NebulaHandshakeDetails
|
||||
@@ -30,47 +31,49 @@ const (
|
||||
fieldResponderIndex = 3 // uint32
|
||||
fieldTime = 5 // uint64
|
||||
fieldCertVersion = 8 // uint32
|
||||
fieldKEMKey = 9 // bytes
|
||||
)
|
||||
|
||||
// MarshalPayload encodes a handshake payload in protobuf wire format compatible
|
||||
// with NebulaHandshake{Details: NebulaHandshakeDetails{...}}.
|
||||
// Returns out (which may be nil), with the marshalled Payload appended to it.
|
||||
func MarshalPayload(out []byte, p Payload) []byte {
|
||||
var details []byte
|
||||
|
||||
if len(p.Cert) > 0 {
|
||||
details = protowire.AppendTag(details, fieldCert, protowire.BytesType)
|
||||
details = protowire.AppendBytes(details, p.Cert)
|
||||
}
|
||||
// Everything but the certificate fits on the stack, which leaves the
|
||||
// certificate the only variable size and out grown just once.
|
||||
var scalars [4 * (1 + binary.MaxVarintLen64)]byte
|
||||
rest := scalars[:0]
|
||||
if p.InitiatorIndex != 0 {
|
||||
details = protowire.AppendTag(details, fieldInitiatorIndex, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.InitiatorIndex))
|
||||
rest = protowire.AppendTag(rest, fieldInitiatorIndex, protowire.VarintType)
|
||||
rest = protowire.AppendVarint(rest, uint64(p.InitiatorIndex))
|
||||
}
|
||||
if p.ResponderIndex != 0 {
|
||||
details = protowire.AppendTag(details, fieldResponderIndex, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.ResponderIndex))
|
||||
rest = protowire.AppendTag(rest, fieldResponderIndex, protowire.VarintType)
|
||||
rest = protowire.AppendVarint(rest, uint64(p.ResponderIndex))
|
||||
}
|
||||
if p.Time != 0 {
|
||||
details = protowire.AppendTag(details, fieldTime, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, p.Time)
|
||||
rest = protowire.AppendTag(rest, fieldTime, protowire.VarintType)
|
||||
rest = protowire.AppendVarint(rest, p.Time)
|
||||
}
|
||||
if p.CertVersion != 0 {
|
||||
details = protowire.AppendTag(details, fieldCertVersion, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.CertVersion))
|
||||
}
|
||||
if len(p.KEMKey) > 0 {
|
||||
details = protowire.AppendTag(details, fieldKEMKey, protowire.BytesType)
|
||||
details = protowire.AppendBytes(details, p.KEMKey)
|
||||
rest = protowire.AppendTag(rest, fieldCertVersion, protowire.VarintType)
|
||||
rest = protowire.AppendVarint(rest, uint64(p.CertVersion))
|
||||
}
|
||||
|
||||
detailsLen := len(rest)
|
||||
if len(p.Cert) > 0 {
|
||||
detailsLen += protowire.SizeTag(fieldCert) + protowire.SizeBytes(len(p.Cert))
|
||||
}
|
||||
out = slices.Grow(out, protowire.SizeTag(1)+protowire.SizeBytes(detailsLen))
|
||||
out = protowire.AppendTag(out, 1, protowire.BytesType)
|
||||
out = protowire.AppendBytes(out, details)
|
||||
|
||||
return out
|
||||
out = protowire.AppendVarint(out, uint64(detailsLen))
|
||||
if len(p.Cert) > 0 {
|
||||
out = protowire.AppendTag(out, fieldCert, protowire.BytesType)
|
||||
out = protowire.AppendBytes(out, p.Cert)
|
||||
}
|
||||
return append(out, rest...)
|
||||
}
|
||||
|
||||
// UnmarshalPayload decodes a protobuf-encoded NebulaHandshake message.
|
||||
// UnmarshalPayload decodes a protobuf-encoded NebulaHandshake message. The
|
||||
// returned Cert aliases b.
|
||||
func UnmarshalPayload(b []byte) (Payload, error) {
|
||||
var p Payload
|
||||
|
||||
@@ -125,7 +128,7 @@ func unmarshalPayloadDetails(p *Payload, b []byte) error {
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.Cert = append([]byte(nil), v...)
|
||||
p.Cert = v
|
||||
b = b[n:]
|
||||
case fieldInitiatorIndex:
|
||||
if typ != protowire.VarintType {
|
||||
@@ -167,16 +170,6 @@ func unmarshalPayloadDetails(p *Payload, b []byte) error {
|
||||
}
|
||||
p.CertVersion = uint32(v)
|
||||
b = b[n:]
|
||||
case fieldKEMKey:
|
||||
if typ != protowire.BytesType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeBytes(b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.KEMKey = append([]byte(nil), v...)
|
||||
b = b[n:]
|
||||
default:
|
||||
n := protowire.ConsumeFieldValue(num, typ, b)
|
||||
if n < 0 {
|
||||
|
||||
+89
-15
@@ -90,6 +90,8 @@ type HandshakeManager struct {
|
||||
// pqCookies and pqCookieLimiter serve cookies while pqTable is under load.
|
||||
pqCookies *pqCookies
|
||||
pqCookieLimiter *ratelimit.Limiter
|
||||
// hybrid holds hybrid handshakes waiting on their third message.
|
||||
hybrid hybridState
|
||||
}
|
||||
|
||||
type HandshakeHostInfo struct {
|
||||
@@ -107,6 +109,9 @@ type HandshakeHostInfo struct {
|
||||
machine *handshake.Machine // The handshake state machine, set during stage 0 (initiator) or beginHandshake (responder multi-message)
|
||||
pq *pqAttempt // The initiator's post-quantum attempt, pending alongside the classical one
|
||||
lastPQ bool // Whether the latest attempt was post-quantum
|
||||
noPQ bool // The post-quantum attempt failed for good, only classical is left
|
||||
|
||||
responder *hybridResponder // Set for a responder's hybrid handshake waiting for msg3
|
||||
}
|
||||
|
||||
func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, st header.MessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
|
||||
@@ -135,6 +140,10 @@ func (hh *HandshakeHostInfo) cachePacket(l *slog.Logger, t header.MessageType, s
|
||||
}
|
||||
|
||||
func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *LightHouse, outside udp.Conn, config HandshakeConfig) *HandshakeManager {
|
||||
// A retrying initiator is answered again at most once per retry interval on
|
||||
// each path its msg1 arrives by.
|
||||
tableCfg := pqTableConfig
|
||||
tableCfg.RepeatInterval = config.tryInterval
|
||||
hm := &HandshakeManager{
|
||||
vpnIps: map[netip.Addr]*HandshakeHostInfo{},
|
||||
indexes: map[uint32]*HandshakeHostInfo{},
|
||||
@@ -148,8 +157,9 @@ func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *Light
|
||||
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
||||
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
||||
l: l,
|
||||
pqTable: fragment.NewTable[pqFragKey, pqFragSource](pqTableConfig),
|
||||
pqTable: fragment.NewTable[pqFragKey, pqFragSource](tableCfg),
|
||||
pqAnswered: newPQAnswered(hsTimeout(config.retries, config.tryInterval)),
|
||||
hybrid: newHybridState(),
|
||||
}
|
||||
pq := config.pq
|
||||
hm.pq.Store(&pq)
|
||||
@@ -174,6 +184,8 @@ func (hm *HandshakeManager) Run(ctx context.Context) {
|
||||
hm.NextOutboundHandshakeTimerTick(now)
|
||||
hm.pqTable.Expire(now)
|
||||
hm.pqAnswered.expire(now)
|
||||
hm.expireHybridResponders(now)
|
||||
hm.tickHybridConfirms(now)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,8 +194,8 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
|
||||
// Gate on known handshake subtypes. Unknown subtypes (or future ones we
|
||||
// don't yet support) are dropped here rather than silently routed through
|
||||
// the IX path. Add a case when introducing a new pattern.
|
||||
switch h.Subtype {
|
||||
case header.HandshakeIXPSK0, pqSubtype:
|
||||
switch {
|
||||
case h.Subtype == header.HandshakeIXPSK0, handshake.IsHybrid(h.Subtype):
|
||||
// supported
|
||||
default:
|
||||
hm.l.Debug("dropping handshake with unsupported subtype",
|
||||
@@ -487,6 +499,13 @@ var (
|
||||
// ErrLocalIndexCollision if we already have an entry in the main or pending
|
||||
// hostmap for the hostinfo.localIndexId.
|
||||
func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface) (*HostInfo, error) {
|
||||
return hm.checkAndComplete(hostinfo, handshakePacket, f, false)
|
||||
}
|
||||
|
||||
// checkAndComplete is CheckAndComplete. committed means the initiator has shown it
|
||||
// uses this tunnel, as a hybrid msg3 does, so an existing tunnel is replaced even
|
||||
// when its handshake is newer.
|
||||
func (hm *HandshakeManager) checkAndComplete(hostinfo *HostInfo, handshakePacket uint8, f *Interface, committed bool) (*HostInfo, error) {
|
||||
hm.mainHostMap.Lock()
|
||||
defer hm.mainHostMap.Unlock()
|
||||
hm.Lock()
|
||||
@@ -503,7 +522,7 @@ func (hm *HandshakeManager) CheckAndComplete(hostinfo *HostInfo, handshakePacket
|
||||
}
|
||||
|
||||
// Is this a newer handshake?
|
||||
if existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
|
||||
if !committed && existingHostInfo.lastHandshakeTime >= hostinfo.lastHandshakeTime && !existingHostInfo.ConnectionState.initiator {
|
||||
return existingHostInfo, ErrExistingHostInfo
|
||||
}
|
||||
|
||||
@@ -775,6 +794,32 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
cs := f.pki.getCertState()
|
||||
|
||||
v := cs.DefaultVersion()
|
||||
allocIndex := func() (uint32, error) { return generateIndex(f.l) }
|
||||
|
||||
// A hybrid responder answers with its v3 certificate and has to wait for msg3,
|
||||
// so its index is registered right away for msg3 to find.
|
||||
var pending *HandshakeHostInfo
|
||||
if handshake.IsHybrid(h.Subtype) {
|
||||
v = cert.Version3
|
||||
pending = &HandshakeHostInfo{
|
||||
hostinfo: &HostInfo{
|
||||
HandshakePacket: make(map[uint8][]byte, 0),
|
||||
relayState: RelayState{
|
||||
relays: nil,
|
||||
relayForByAddr: map[netip.Addr]*Relay{},
|
||||
relayForByIdx: map[uint32]*Relay{},
|
||||
},
|
||||
},
|
||||
startTime: time.Now(),
|
||||
responder: &hybridResponder{},
|
||||
}
|
||||
// The index is visible to msg3 as soon as it is allocated, so hold the
|
||||
// entry until it is filled in.
|
||||
pending.Lock()
|
||||
defer pending.Unlock()
|
||||
allocIndex = func() (uint32, error) { return hm.allocateIndex(pending) }
|
||||
}
|
||||
|
||||
if cs.GetCredential(v) == nil {
|
||||
f.l.Error("Unable to handshake with host because no certificate is available",
|
||||
"from", via, "certVersion", v)
|
||||
@@ -783,7 +828,7 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
machine, err := handshake.NewMachine(
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
|
||||
hm.certVerifier(), allocIndex,
|
||||
false, h.Subtype,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -793,10 +838,18 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
|
||||
response, result, err := machine.ProcessPacket(nil, packet)
|
||||
if err != nil {
|
||||
if pending != nil {
|
||||
hm.DeleteHostInfo(pending.hostinfo)
|
||||
}
|
||||
f.l.Error("Failed to process handshake packet", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if result == nil && pending != nil {
|
||||
hm.awaitMsg3(via, pending, machine, packet, response, received)
|
||||
return
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
// Multi-message pattern: the responder Machine would need to be
|
||||
// registered in hm.indexes so a future inbound packet finds it via
|
||||
@@ -821,6 +874,13 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
return
|
||||
}
|
||||
|
||||
// A classical attempt crossing the peer's hybrid one goes unanswered.
|
||||
if !handshake.IsHybrid(machine.Subtype()) && hm.crossesHybrid(vpnAddrs, time.Now()) {
|
||||
f.l.Debug("Ignoring classical handshake that crossed a hybrid one",
|
||||
"vpnAddrs", vpnAddrs, "from", via, "window", hm.hybridWindow())
|
||||
return
|
||||
}
|
||||
|
||||
connState, err := newConnectionStateFromResult(result)
|
||||
if err != nil {
|
||||
f.l.Error("Discarding handshake with an invalid message index", "error", err, "vpnAddrs", vpnAddrs)
|
||||
@@ -938,22 +998,28 @@ func (hm *HandshakeManager) processResponse(via ViaSender, hh *HandshakeHostInfo
|
||||
response, result, err := machine.ProcessPacket(nil, packet)
|
||||
if err != nil {
|
||||
// Recoverable errors are routine noise, log at Debug. Fatal errors get a Warn.
|
||||
if machine.Failed() {
|
||||
if !machine.Failed() {
|
||||
f.l.Debug("Failed to process handshake packet",
|
||||
"vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
} else if hh.pq != nil && machine == hh.pq.machine && !hm.pqConfig().require {
|
||||
// A post-quantum attempt can fail where the classical one would not, a v3
|
||||
// certificate from a CA only trusted in its v2 form for one. Keep going
|
||||
// with classical alone.
|
||||
f.l.Warn("Failed to process post-quantum handshake packet, continuing with classical",
|
||||
"vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
hm.abandonPQ(hh)
|
||||
} else {
|
||||
f.l.Warn("Failed to process handshake packet, abandoning",
|
||||
"vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
hm.DeleteHostInfo(hostinfo)
|
||||
} else {
|
||||
f.l.Debug("Failed to process handshake packet",
|
||||
"vpnAddrs", hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if response != nil {
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false, 0)
|
||||
}
|
||||
|
||||
if result == nil {
|
||||
if response != nil {
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false, 0)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1068,6 +1134,12 @@ func (hm *HandshakeManager) processResponse(via ViaSender, hh *HandshakeHostInfo
|
||||
hm.Complete(hostinfo, f)
|
||||
hm.notePQPeer(machine.Subtype(), vpnAddrs)
|
||||
|
||||
// A three message pattern finishes with our msg3, which goes out before any
|
||||
// cached packets do and keeps going until the responder is heard from.
|
||||
if response != nil {
|
||||
hm.startHybridConfirm(via, hostinfo, response, result.MessageIndex)
|
||||
}
|
||||
|
||||
if len(hh.packetStore) > 0 {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("Sending stored packets", "count", len(hh.packetStore))
|
||||
@@ -1166,7 +1238,9 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
||||
"initiatorIndex", hostinfo.remoteIndexId,
|
||||
"responderIndex", hostinfo.localIndexId,
|
||||
}
|
||||
if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
|
||||
if hostinfo.ConnectionState == nil {
|
||||
// A hybrid responder answers msg1 before it has keys.
|
||||
} else if peerCert := hostinfo.ConnectionState.peerCert; peerCert != nil {
|
||||
logFields = append(logFields,
|
||||
"certName", peerCert.Certificate.Name(),
|
||||
"certVersion", peerCert.Certificate.Version(),
|
||||
@@ -1177,7 +1251,7 @@ func (hm *HandshakeManager) sendHandshakeResponse(via ViaSender, msg []byte, hos
|
||||
|
||||
if header.IsFragmented(subtype) {
|
||||
fields := append(logFields, "from", via)
|
||||
if err := hm.sendFragmentedResponse(via, msg, hostinfo, cached, received); err != nil {
|
||||
if err := hm.sendFragmentedResponse(via, msg, hostinfo, received); err != nil {
|
||||
f.l.Debug("Did not send handshake message", append(fields, "error", err)...)
|
||||
} else {
|
||||
f.l.Info("Handshake message sent", fields...)
|
||||
|
||||
@@ -0,0 +1,455 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
// Hybrid handshakes (ix_hybrid_mlkem1024) take three messages, so unlike IX the
|
||||
// responder has to wait for one more message and the initiator finishes by
|
||||
// sending rather than receiving:
|
||||
//
|
||||
// - The responder answers msg1 with msg2 and keeps the handshake pending under
|
||||
// its local index until msg3 arrives. Data for that index is dropped quietly
|
||||
// meanwhile, it must not draw a RecvError. Once msg3 verifies the tunnel
|
||||
// goes live and an empty TestReply tells the initiator so.
|
||||
// - The initiator has the keys as soon as it writes msg3, so the tunnel goes
|
||||
// live then, readable only by the real responder. msg3 is resent with fresh
|
||||
// symbols until something from the responder decrypts, and if nothing does
|
||||
// within the handshake timeout the tunnel is closed.
|
||||
|
||||
const (
|
||||
// hybridMsg3MaxLen bounds the msg3 a pending responder reassembles. msg3 is
|
||||
// a ciphertext and two tags, about 1.6KB.
|
||||
hybridMsg3MaxLen = 4096
|
||||
)
|
||||
|
||||
// hybridResponder is the responder half of a pending hybrid handshake, waiting
|
||||
// for msg3.
|
||||
type hybridResponder struct {
|
||||
msg3 *fragment.Assembly
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// hybridConfirm is an initiator's completed hybrid handshake that has not yet
|
||||
// heard from the responder.
|
||||
type hybridConfirm struct {
|
||||
hostinfo *HostInfo
|
||||
subtype header.MessageSubType
|
||||
sender *fragment.Sender
|
||||
send func([]byte) error
|
||||
handshakeLen uint64 // messages the handshake took, which the replay window was seeded with
|
||||
deadline time.Time
|
||||
next time.Time
|
||||
attempts int
|
||||
}
|
||||
|
||||
// hybridState holds the hybrid handshakes waiting on their last step.
|
||||
type hybridState struct {
|
||||
// responders maps local indexes to pending responders. Guarded by the
|
||||
// HandshakeManager lock; the entries are also in its indexes.
|
||||
responders map[uint32]*HandshakeHostInfo
|
||||
|
||||
confirmsMu sync.Mutex
|
||||
confirms map[*HostInfo]*hybridConfirm
|
||||
|
||||
// answered holds when this responder answered each peer's latest new
|
||||
// hybrid msg1, for the crossing window.
|
||||
answeredMu sync.Mutex
|
||||
answered map[netip.Addr]time.Time
|
||||
}
|
||||
|
||||
func newHybridState() hybridState {
|
||||
return hybridState{
|
||||
responders: map[uint32]*HandshakeHostInfo{},
|
||||
confirms: map[*HostInfo]*hybridConfirm{},
|
||||
answered: map[netip.Addr]time.Time{},
|
||||
}
|
||||
}
|
||||
|
||||
// A peer that sent a hybrid msg1 alternates, and its first classical attempt
|
||||
// follows anywhere from right away to three retry intervals later: the retry
|
||||
// timer is set one interval out, lands two slots ahead on the timer wheel, and
|
||||
// the wheel only moves on whole ticks of the manager's clock. Answering that
|
||||
// classical msg1 races the hybrid handshake and leaves a classical tunnel behind
|
||||
// on the responder whichever wins. So for four retry intervals after answering a
|
||||
// peer's hybrid msg1, its classical msg1s go unanswered; the crossing one arrives
|
||||
// within that wherever the round trip, since both travel the same path. The
|
||||
// window is short on purpose: an initiator whose hybrid attempt fails on its own
|
||||
// side, say one that does not trust our v3 CA yet, still gets a classical answer
|
||||
// to a later attempt. Blocking for as long as any hybrid state remains would
|
||||
// refuse it until its handshake timed out, and its next handshake would start
|
||||
// with a hybrid msg1 again.
|
||||
|
||||
// hybridWindow is how long classical msg1s go unanswered after a hybrid msg1.
|
||||
func (hm *HandshakeManager) hybridWindow() time.Duration {
|
||||
return 4 * hm.config.tryInterval
|
||||
}
|
||||
|
||||
// noteHybridMsg1 opens the crossing window for a peer whose new hybrid msg1 this
|
||||
// responder answered.
|
||||
func (hm *HandshakeManager) noteHybridMsg1(vpnAddrs []netip.Addr, now time.Time) {
|
||||
hm.hybrid.answeredMu.Lock()
|
||||
defer hm.hybrid.answeredMu.Unlock()
|
||||
for _, a := range vpnAddrs {
|
||||
hm.hybrid.answered[a] = now
|
||||
}
|
||||
}
|
||||
|
||||
// crossesHybrid reports whether a classical msg1 from a peer arrived within the
|
||||
// crossing window of its hybrid msg1.
|
||||
func (hm *HandshakeManager) crossesHybrid(vpnAddrs []netip.Addr, now time.Time) bool {
|
||||
hm.hybrid.answeredMu.Lock()
|
||||
defer hm.hybrid.answeredMu.Unlock()
|
||||
for _, a := range vpnAddrs {
|
||||
if at, ok := hm.hybrid.answered[a]; ok && now.Sub(at) < hm.hybridWindow() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// awaitMsg3 keeps a responder's hybrid handshake pending after msg1, and sends
|
||||
// msg2. hh is already in the indexes under the local index the Machine
|
||||
// allocated.
|
||||
func (hm *HandshakeManager) awaitMsg3(via ViaSender, hh *HandshakeHostInfo, machine *handshake.Machine, packet, response []byte, received int) {
|
||||
f := hm.f
|
||||
hostinfo := hh.hostinfo
|
||||
|
||||
remoteCert := machine.PeerCert()
|
||||
if remoteCert == nil {
|
||||
f.l.Error("Handshake did not produce a peer certificate", "from", via)
|
||||
hm.DeleteHostInfo(hostinfo)
|
||||
return
|
||||
}
|
||||
vpnAddrs, anyVpnAddrsInCommon, ok := hm.validatePeerCert(via, remoteCert)
|
||||
if !ok {
|
||||
hm.DeleteHostInfo(hostinfo)
|
||||
return
|
||||
}
|
||||
var rh header.H
|
||||
if err := rh.Parse(response); err != nil {
|
||||
hm.DeleteHostInfo(hostinfo)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
hostinfo.vpnAddrs = vpnAddrs
|
||||
hostinfo.remoteIndexId = rh.RemoteIndex
|
||||
// A hybrid msg1 is always fragmented, so packet is the one the fragment
|
||||
// table reassembled, not the listener's buffer, and nothing else holds it.
|
||||
hostinfo.HandshakePacket[handshakePacketStage0] = packet[header.Len:]
|
||||
hostinfo.HandshakePacket[handshakePacketStage2] = response
|
||||
hostinfo.remotes = f.lightHouse.QueryCache(vpnAddrs)
|
||||
if !via.IsRelayed {
|
||||
hostinfo.SetRemote(via.UdpAddr)
|
||||
}
|
||||
hh.machine = machine
|
||||
hh.responder.expires = now.Add(hsTimeout(hm.config.retries, hm.config.tryInterval))
|
||||
|
||||
hm.Lock()
|
||||
hm.hybrid.responders[hostinfo.localIndexId] = hh
|
||||
hm.Unlock()
|
||||
|
||||
msg := "Handshake message received"
|
||||
if !anyVpnAddrsInCommon {
|
||||
msg = "Handshake message received, but no vpnNetworks in common."
|
||||
}
|
||||
f.l.Info(msg,
|
||||
"vpnAddrs", vpnAddrs,
|
||||
"from", via,
|
||||
"certName", remoteCert.Certificate.Name(),
|
||||
"certVersion", remoteCert.Certificate.Version(),
|
||||
"fingerprint", remoteCert.Fingerprint,
|
||||
"issuer", remoteCert.Certificate.Issuer(),
|
||||
"initiatorIndex", hostinfo.remoteIndexId,
|
||||
"responderIndex", hostinfo.localIndexId,
|
||||
"handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
|
||||
)
|
||||
|
||||
hm.sendHandshakeResponse(via, response, hostinfo, false, received)
|
||||
hm.pqAnswered.add(packet[header.Len:], hostinfo, now)
|
||||
hm.noteHybridMsg1(vpnAddrs, now)
|
||||
}
|
||||
|
||||
// continueHybridResponder collects msg3 fragments for a pending responder and
|
||||
// completes the tunnel once they decode and verify.
|
||||
func (hm *HandshakeManager) continueHybridResponder(via ViaSender, h *header.H, fh fragment.Header, sym []byte) {
|
||||
hh := hm.queryIndex(h.RemoteIndex)
|
||||
if hh == nil || hh.responder == nil {
|
||||
hm.reconfirmHybrid(h.RemoteIndex)
|
||||
return
|
||||
}
|
||||
if fh.MsgLen > hybridMsg3MaxLen {
|
||||
return
|
||||
}
|
||||
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
if !hm.stillPending(hh, h.RemoteIndex) || fh.FragID != hh.hostinfo.remoteIndexId {
|
||||
return
|
||||
}
|
||||
|
||||
r := hh.responder
|
||||
if r.msg3 == nil {
|
||||
a, err := fragment.NewAssembly(fh)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
r.msg3 = a
|
||||
}
|
||||
ready, err := r.msg3.Add(fh, sym)
|
||||
if errors.Is(err, fragment.ErrMismatch) {
|
||||
r.msg3 = nil
|
||||
return
|
||||
}
|
||||
if err != nil || !ready {
|
||||
return
|
||||
}
|
||||
pkt, err := r.msg3.Decode(make([]byte, header.Len))
|
||||
r.msg3 = nil
|
||||
if err != nil {
|
||||
hm.l.Debug("failed to decode handshake fragments", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, result, err := hh.machine.ProcessPacket(nil, reassembled(h, pkt))
|
||||
if err != nil {
|
||||
if hh.machine.Failed() {
|
||||
hm.l.Warn("Failed to process handshake packet, abandoning",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
hm.forgetHybridResponder(hh)
|
||||
} else {
|
||||
hm.l.Debug("Failed to process handshake packet",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "from", via, "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if result == nil {
|
||||
return
|
||||
}
|
||||
hm.completeHybridResponder(via, hh, result)
|
||||
}
|
||||
|
||||
// completeHybridResponder brings up the tunnel of a responder whose msg3 verified.
|
||||
// The caller must hold hh.Lock.
|
||||
func (hm *HandshakeManager) completeHybridResponder(via ViaSender, hh *HandshakeHostInfo, result *handshake.Result) {
|
||||
f := hm.f
|
||||
hostinfo := hh.hostinfo
|
||||
machine := hh.machine
|
||||
defer hm.forgetHybridResponder(hh)
|
||||
|
||||
cs, err := newConnectionStateFromResult(result)
|
||||
if err != nil {
|
||||
f.l.Error("Discarding handshake with an invalid message index", "error", err, "vpnAddrs", hostinfo.vpnAddrs)
|
||||
return
|
||||
}
|
||||
hostinfo.ConnectionState = cs
|
||||
hostinfo.remoteIndexId = result.RemoteIndex
|
||||
hostinfo.lastHandshakeTime = result.HandshakeTime
|
||||
// The initiator sends msg3 by the path its msg2 got through, so that path
|
||||
// works both ways: send by it. A relayed msg3 also means the direct address
|
||||
// learned from msg1 may only work toward us, so forget it and let traffic,
|
||||
// the confirmation first, go by the relay.
|
||||
if !via.IsRelayed {
|
||||
hostinfo.SetRemote(via.UdpAddr)
|
||||
} else {
|
||||
hostinfo.remote.Store(nil)
|
||||
hostinfo.relayState.InsertRelayTo(via.relayHI.vpnAddrs[0])
|
||||
}
|
||||
remoteCert := result.RemoteCert
|
||||
hostinfo.buildNetworks(f.myVpnNetworksTable, remoteCert.Certificate)
|
||||
|
||||
// The initiator only sends msg3 once it settled on this handshake, so this
|
||||
// tunnel wins even over a newer one: a classical attempt that crossed it, say,
|
||||
// which the initiator has already given up on.
|
||||
existing, err := hm.checkAndComplete(hostinfo, handshakePacketStage0, f, true)
|
||||
if err != nil {
|
||||
hm.handleCheckAndCompleteError(err, existing, hostinfo, via, machine.Subtype(), 0)
|
||||
return
|
||||
}
|
||||
|
||||
f.l.Info("Handshake completed",
|
||||
"vpnAddrs", hostinfo.vpnAddrs,
|
||||
"from", via,
|
||||
"certName", remoteCert.Certificate.Name(),
|
||||
"certVersion", remoteCert.Certificate.Version(),
|
||||
"fingerprint", remoteCert.Fingerprint,
|
||||
"issuer", remoteCert.Certificate.Issuer(),
|
||||
"initiatorIndex", result.RemoteIndex,
|
||||
"responderIndex", result.LocalIndex,
|
||||
"handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
|
||||
"durationNs", time.Since(hh.startTime).Nanoseconds(),
|
||||
)
|
||||
|
||||
// Let the initiator know, even if there is no traffic to do it.
|
||||
hostinfo.handshakeResendAt.Store(time.Now().UnixNano())
|
||||
hm.sendHybridConfirmation(hostinfo)
|
||||
|
||||
hm.notePQPeer(machine.Subtype(), hostinfo.vpnAddrs)
|
||||
hostinfo.remotes.RefreshFromHandshake(hostinfo.vpnAddrs)
|
||||
if f.lightHouse.IsAnyLighthouseAddr(hostinfo.vpnAddrs) {
|
||||
f.lightHouse.TriggerUpdate()
|
||||
}
|
||||
}
|
||||
|
||||
func (hm *HandshakeManager) sendHybridConfirmation(hostinfo *HostInfo) {
|
||||
// The reply is empty, so even relayed it is just two headers and two tags.
|
||||
cs := hostinfo.ConnectionState
|
||||
out := make([]byte, 2*(header.Len+cs.eKey.Overhead()))
|
||||
hm.f.send(header.Test, header.TestReply, cs, hostinfo, []byte{}, make([]byte, 12, 12), out)
|
||||
}
|
||||
|
||||
// reconfirmHybrid answers a msg3 for a hybrid tunnel this responder already
|
||||
// completed: the initiator is still resending it, so the confirmation was lost.
|
||||
// Replies are rate limited to one per retry interval and go to the tunnel's
|
||||
// remote, never to wherever the fragment claims to come from.
|
||||
func (hm *HandshakeManager) reconfirmHybrid(index uint32) {
|
||||
hostinfo := hm.mainHostMap.QueryIndex(index)
|
||||
if hostinfo == nil || hostinfo.ConnectionState == nil || hostinfo.ConnectionState.initiator {
|
||||
return
|
||||
}
|
||||
if pc := hostinfo.ConnectionState.peerCert; pc == nil || pc.Certificate.Version() != cert.Version3 {
|
||||
return
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
last := hostinfo.handshakeResendAt.Load()
|
||||
if now-last < int64(hm.config.tryInterval) || !hostinfo.handshakeResendAt.CompareAndSwap(last, now) {
|
||||
return
|
||||
}
|
||||
hm.sendHybridConfirmation(hostinfo)
|
||||
}
|
||||
|
||||
// forgetHybridResponder releases a pending responder's index.
|
||||
func (hm *HandshakeManager) forgetHybridResponder(hh *HandshakeHostInfo) {
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
idx := hh.hostinfo.localIndexId
|
||||
if hm.indexes[idx] == hh {
|
||||
delete(hm.indexes, idx)
|
||||
}
|
||||
if hm.hybrid.responders[idx] == hh {
|
||||
delete(hm.hybrid.responders, idx)
|
||||
}
|
||||
}
|
||||
|
||||
// isHybridResponder reports whether index belongs to a responder still waiting
|
||||
// for msg3, whose initiator may already be sending data.
|
||||
func (hm *HandshakeManager) isHybridResponder(index uint32) bool {
|
||||
hm.RLock()
|
||||
defer hm.RUnlock()
|
||||
_, ok := hm.hybrid.responders[index]
|
||||
return ok
|
||||
}
|
||||
|
||||
// expireHybridResponders drops responders that never got their msg3.
|
||||
func (hm *HandshakeManager) expireHybridResponders(now time.Time) {
|
||||
hm.hybrid.answeredMu.Lock()
|
||||
for a, at := range hm.hybrid.answered {
|
||||
if now.Sub(at) >= hm.hybridWindow() {
|
||||
delete(hm.hybrid.answered, a)
|
||||
}
|
||||
}
|
||||
hm.hybrid.answeredMu.Unlock()
|
||||
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
for idx, hh := range hm.hybrid.responders {
|
||||
if now.After(hh.responder.expires) {
|
||||
if hm.indexes[idx] == hh {
|
||||
delete(hm.indexes, idx)
|
||||
}
|
||||
delete(hm.hybrid.responders, idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// startHybridConfirm sends an initiator's msg3 and keeps resending it until the
|
||||
// responder is heard from on the new tunnel.
|
||||
func (hm *HandshakeManager) startHybridConfirm(via ViaSender, hostinfo *HostInfo, msg3 []byte, handshakeLen uint64) {
|
||||
var h header.H
|
||||
if err := h.Parse(msg3); err != nil {
|
||||
return
|
||||
}
|
||||
s, err := fragment.NewSender(msg3[header.Len:], h.Subtype, h.RemoteIndex, h.MessageCounter, hostinfo.localIndexId)
|
||||
if err != nil {
|
||||
hostinfo.logger(hm.l).Error("Failed to fragment handshake", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
c := &hybridConfirm{
|
||||
hostinfo: hostinfo,
|
||||
subtype: h.Subtype,
|
||||
sender: s,
|
||||
send: hm.sendTo(via),
|
||||
handshakeLen: handshakeLen,
|
||||
deadline: now.Add(hsTimeout(hm.config.retries, hm.config.tryInterval)),
|
||||
next: now.Add(hm.config.tryInterval),
|
||||
attempts: 1,
|
||||
}
|
||||
hm.hybrid.confirmsMu.Lock()
|
||||
hm.hybrid.confirms[hostinfo] = c
|
||||
hm.hybrid.confirmsMu.Unlock()
|
||||
hm.sendHybridMsg3(c)
|
||||
}
|
||||
|
||||
func (hm *HandshakeManager) sendHybridMsg3(c *hybridConfirm) {
|
||||
pkts, later, err := c.sender.Attempt(fragment.DefaultRepair(c.sender.Layout().K))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hm.messageMetrics.Tx(header.Handshake, c.subtype, int64(len(pkts)+len(later)))
|
||||
// No repair delay: the packets cached during the handshake go out right
|
||||
// behind msg3, and the responder drops whatever arrives before msg3
|
||||
// completes. With the repair trailing, losing either data fragment would
|
||||
// cost them. msg3 is four packets, too short for the tail drop the delay
|
||||
// guards against.
|
||||
if err := hm.sendFragmentedAfter(pkts, later, c.send, 0); err != nil {
|
||||
c.hostinfo.logger(hm.l).Debug("Failed to send handshake message", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// tickHybridConfirms resends msg3 to responders not heard from yet, and closes
|
||||
// tunnels whose responder never was.
|
||||
func (hm *HandshakeManager) tickHybridConfirms(now time.Time) {
|
||||
var resend, closing []*hybridConfirm
|
||||
hm.hybrid.confirmsMu.Lock()
|
||||
for hostinfo, c := range hm.hybrid.confirms {
|
||||
switch {
|
||||
case hm.mainHostMap.QueryIndex(hostinfo.localIndexId) != hostinfo:
|
||||
delete(hm.hybrid.confirms, hostinfo)
|
||||
case hostinfo.ConnectionState.heardFromPeer(c.handshakeLen):
|
||||
delete(hm.hybrid.confirms, hostinfo)
|
||||
case now.After(c.deadline):
|
||||
delete(hm.hybrid.confirms, hostinfo)
|
||||
closing = append(closing, c)
|
||||
case !now.Before(c.next):
|
||||
c.attempts++
|
||||
c.next = now.Add(hm.config.tryInterval * time.Duration(c.attempts))
|
||||
resend = append(resend, c)
|
||||
}
|
||||
}
|
||||
hm.hybrid.confirmsMu.Unlock()
|
||||
|
||||
for _, c := range resend {
|
||||
if hm.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
c.hostinfo.logger(hm.l).Debug("Resending handshake message, responder not heard from yet", "attempts", c.attempts)
|
||||
}
|
||||
hm.sendHybridMsg3(c)
|
||||
}
|
||||
for _, c := range closing {
|
||||
c.hostinfo.logger(hm.l).Info("Responder never confirmed the handshake, closing tunnel",
|
||||
"localIndex", c.hostinfo.localIndexId, "remoteIndex", c.hostinfo.remoteIndexId)
|
||||
hm.f.closeTunnel(c.hostinfo)
|
||||
}
|
||||
}
|
||||
+204
-65
@@ -12,6 +12,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
@@ -19,9 +20,6 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// pqSubtype is the post-quantum handshake this node speaks.
|
||||
pqSubtype = header.HandshakeIXPSK2MLKEM1024
|
||||
|
||||
// DefaultPQRepairDelay is how long repair fragments trail the data fragments.
|
||||
DefaultPQRepairDelay = 10 * time.Millisecond
|
||||
|
||||
@@ -30,13 +28,19 @@ const (
|
||||
pqAmplification = 3
|
||||
)
|
||||
|
||||
// pqMaxMsgLen bounds the fragmented handshake messages a node reassembles:
|
||||
// msg1 in the responder's table and msg2 in an initiator's slots. The largest
|
||||
// is msg2 at about 9.6KB, which leaves room for certificates carrying many
|
||||
// names and routes.
|
||||
const pqMaxMsgLen = 16384
|
||||
|
||||
// pqTableConfig bounds the responder's reassembly of msg1 fragments from senders
|
||||
// that have not authenticated yet.
|
||||
var pqTableConfig = fragment.TableConfig{
|
||||
MaxBytes: 4 << 20,
|
||||
MaxEntries: 1024,
|
||||
MaxPerSource: 4,
|
||||
MaxMsgLen: 16384,
|
||||
MaxMsgLen: pqMaxMsgLen,
|
||||
TTL: 3 * time.Second,
|
||||
}
|
||||
|
||||
@@ -68,6 +72,17 @@ func (hm *HandshakeManager) pqConfig() *pqHandshakeConfig {
|
||||
return hm.pq.Load()
|
||||
}
|
||||
|
||||
// warnPQWithoutV3 says so when post-quantum settings are on but the node has no
|
||||
// version 3 certificate: post-quantum handshakes are hybrid only, so they do
|
||||
// nothing until it has one. require is refused outright when loading pki.
|
||||
func warnPQWithoutV3(l *slog.Logger, cfg pqHandshakeConfig, cs *CertState) {
|
||||
if _, ok := cs.hybridSubtype(); ok || !(cfg.initiate || cfg.accept || cfg.sticky) {
|
||||
return
|
||||
}
|
||||
l.Warn("handshakes.pq has no effect without a version 3 certificate in pki.cert",
|
||||
"initiate", cfg.initiate, "accept", cfg.accept, "sticky", cfg.sticky)
|
||||
}
|
||||
|
||||
// reloadPQ applies changed post-quantum settings. Handshakes already in flight
|
||||
// keep going; the new settings apply to the next attempt and packet.
|
||||
func (hm *HandshakeManager) reloadPQ(c *config.C) {
|
||||
@@ -76,6 +91,12 @@ func (hm *HandshakeManager) reloadPQ(c *config.C) {
|
||||
}
|
||||
old := hm.pqConfig()
|
||||
cfg := pqHandshakeConfigFrom(c)
|
||||
cs := hm.f.pki.getCertState()
|
||||
if _, ok := cs.hybridSubtype(); cfg.require && !ok {
|
||||
hm.l.Error("Refusing handshakes.pq.require without a version 3 certificate in pki.cert, keeping the previous settings")
|
||||
return
|
||||
}
|
||||
warnPQWithoutV3(hm.l, cfg, cs)
|
||||
hm.pq.Store(&cfg)
|
||||
hm.l.Info("Post-quantum handshake settings changed",
|
||||
"initiate", cfg.initiate, "oldInitiate", old.initiate,
|
||||
@@ -86,16 +107,88 @@ func (hm *HandshakeManager) reloadPQ(c *config.C) {
|
||||
)
|
||||
}
|
||||
|
||||
// pqMsg2Slots is how many responders' msg2s one attempt reassembles at once.
|
||||
// Two hosts answer the same msg1 when a stale lighthouse address for the peer
|
||||
// belongs to another node now. Both answers name this attempt in RemoteIndex
|
||||
// and differ only in FragID, the responder's own index. A single assembly that
|
||||
// emptied on a FragID change let the two interleaved bursts wipe each other
|
||||
// out, and since hearing any msg2 fragment stops the classical turns, the
|
||||
// retries only repeated it (up to three extra attempts in e2e). One slot per
|
||||
// FragID lets whichever answer completes first be processed; a wrong host's
|
||||
// answer then takes the existing block-and-retry path.
|
||||
const pqMsg2Slots = 2
|
||||
|
||||
// msg2Slot reassembles one responder's msg2.
|
||||
type msg2Slot struct {
|
||||
fragID uint32
|
||||
msgLen uint16
|
||||
a *fragment.Assembly
|
||||
}
|
||||
|
||||
// pqAttempt is the initiator's post-quantum attempt for a pending handshake. It
|
||||
// lives alongside the classical attempt in HandshakeHostInfo and has its own
|
||||
// local index, so whichever answer arrives first wins.
|
||||
type pqAttempt struct {
|
||||
machine *handshake.Machine
|
||||
subtype header.MessageSubType
|
||||
index uint32
|
||||
sender *fragment.Sender
|
||||
msg2 *fragment.Assembly
|
||||
cookieResendAt time.Time // last resend prompted by a cookie reply
|
||||
heard bool // a msg2 fragment or cookie reply arrived, so the peer speaks PQ
|
||||
msg2 [pqMsg2Slots]msg2Slot // an array, not a map: one slot is used nearly always
|
||||
cookieResendAt time.Time // last resend prompted by a cookie reply
|
||||
heard bool // a msg2 fragment or cookie reply arrived, so the peer speaks PQ
|
||||
}
|
||||
|
||||
// slotFor returns the assembly collecting msg2 fragments with fh's FragID,
|
||||
// starting one if there is none. A responder never changes its FragID or
|
||||
// MsgLen, so a fragment whose MsgLen disagrees with its slot is a stray or a
|
||||
// forgery and starts that slot over. When every slot is taken the one holding
|
||||
// the least is replaced: a third responder is vanishingly rare, and a forged
|
||||
// FragID could already spoil an attempt. It returns nil if no assembly can be
|
||||
// made for fh.
|
||||
func (pq *pqAttempt) slotFor(fh fragment.Header) *fragment.Assembly {
|
||||
victim := -1
|
||||
for i := range pq.msg2 {
|
||||
s := &pq.msg2[i]
|
||||
if s.a != nil && s.fragID == fh.FragID {
|
||||
if s.msgLen == fh.MsgLen {
|
||||
return s.a
|
||||
}
|
||||
victim = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if victim < 0 {
|
||||
for i := range pq.msg2 {
|
||||
if pq.msg2[i].a == nil {
|
||||
victim = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if victim < 0 {
|
||||
victim = 0
|
||||
for i := 1; i < len(pq.msg2); i++ {
|
||||
if pq.msg2[i].a.Stored() < pq.msg2[victim].a.Stored() {
|
||||
victim = i
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
a, err := fragment.NewAssembly(fh)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
pq.msg2[victim] = msg2Slot{fragID: fh.FragID, msgLen: fh.MsgLen, a: a}
|
||||
return a
|
||||
}
|
||||
|
||||
// dropSlot releases the slot holding a.
|
||||
func (pq *pqAttempt) dropSlot(a *fragment.Assembly) {
|
||||
for i := range pq.msg2 {
|
||||
if pq.msg2[i].a == a {
|
||||
pq.msg2[i] = msg2Slot{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// pqFragKey identifies one msg1 being reassembled.
|
||||
@@ -126,12 +219,11 @@ func pqFragKeyFor(via ViaSender, fragID uint32) (pqFragKey, pqFragSource) {
|
||||
return pqFragKey{addr: via.UdpAddr, fragID: fragID}, pqFragSource{prefix: prefix}
|
||||
}
|
||||
|
||||
// reassembled rebuilds the packet the handshake Machine expects from the header
|
||||
// of a fragment and the decoded message.
|
||||
func reassembled(h *header.H, msg []byte) []byte {
|
||||
p := make([]byte, header.Len, header.Len+len(msg))
|
||||
header.Encode(p, header.Version, header.Handshake, h.Subtype, h.RemoteIndex, h.MessageCounter)
|
||||
return append(p, msg...)
|
||||
// reassembled turns a decoded message into the packet the handshake Machine
|
||||
// expects, by writing the header of one of its fragments into the header.Len
|
||||
// bytes left for it in front of the message.
|
||||
func reassembled(h *header.H, pkt []byte) []byte {
|
||||
return header.Encode(pkt, header.Version, header.Handshake, h.Subtype, h.RemoteIndex, h.MessageCounter)[:len(pkt)]
|
||||
}
|
||||
|
||||
// usePQ decides whether this outbound attempt is post-quantum. A peer that does
|
||||
@@ -144,8 +236,11 @@ func reassembled(h *header.H, msg []byte) []byte {
|
||||
// it, so classical stops getting turns.
|
||||
func (hm *HandshakeManager) usePQ(hh *HandshakeHostInfo, vpnIp netip.Addr, triggered bool) bool {
|
||||
cfg := hm.pqConfig()
|
||||
if _, ok := hm.f.pki.getCertState().hybridSubtype(); !ok {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case !cfg.initiate:
|
||||
case !cfg.initiate, hh.noPQ:
|
||||
return false
|
||||
case cfg.require:
|
||||
return true
|
||||
@@ -194,26 +289,41 @@ func (hm *HandshakeManager) relayEstablished(target netip.Addr, relayHI *HostInf
|
||||
f := hm.f
|
||||
hh.hostinfo.logger(hm.l).Info("Send handshake via new relay", "relay", relayHI.vpnAddrs[0])
|
||||
_ = hm.sendFragmented(now, later, func(p []byte) error {
|
||||
f.SendVia(relayHI, relay, p, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||
f.sendHandshakeVia(relayHI, relay, p)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// buildPQAttempt creates the initiator's PQ Machine and msg1 sender.
|
||||
// sendHandshakeVia sends a handshake packet through a relay, with buffers sized
|
||||
// for the packet rather than the mtu: a relayed post-quantum handshake is
|
||||
// dozens of fragments.
|
||||
func (f *Interface) sendHandshakeVia(via *HostInfo, relay *Relay, p []byte) {
|
||||
out := make([]byte, header.Len+len(p)+via.ConnectionState.eKey.Overhead())
|
||||
f.SendVia(via, relay, p, make([]byte, 12), out, false, 0)
|
||||
}
|
||||
|
||||
// buildPQAttempt creates the initiator's PQ Machine and msg1 sender. A node with
|
||||
// a v3 certificate speaks the hybrid handshake for its suite's KEM, anyone else
|
||||
// the ephemeral KEM one.
|
||||
func (hm *HandshakeManager) buildPQAttempt(hh *HandshakeHostInfo) bool {
|
||||
cs := hm.f.pki.getCertState()
|
||||
v := hm.initiatingVersion(hh, cs)
|
||||
subtype, ok := cs.hybridSubtype()
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
v = cert.Version3
|
||||
if cs.GetCredential(v) == nil {
|
||||
hm.f.l.Error("Unable to handshake with host because no certificate is available",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "certVersion", v)
|
||||
return false
|
||||
}
|
||||
|
||||
pq := &pqAttempt{}
|
||||
pq := &pqAttempt{subtype: subtype}
|
||||
machine, err := handshake.NewMachine(
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return hm.allocatePQIndex(hh, pq) },
|
||||
true, pqSubtype,
|
||||
true, subtype,
|
||||
)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to create handshake machine",
|
||||
@@ -229,7 +339,7 @@ func (hm *HandshakeManager) buildPQAttempt(hh *HandshakeHostInfo) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
sender, err := fragment.NewSender(msg[header.Len:], pqSubtype, 0, 1, pq.index)
|
||||
sender, err := fragment.NewSender(msg[header.Len:], subtype, 0, 1, pq.index)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to fragment handshake",
|
||||
"vpnAddrs", hh.hostinfo.vpnAddrs, "error", err)
|
||||
@@ -271,6 +381,14 @@ func (hm *HandshakeManager) allocatePQIndex(hh *HandshakeHostInfo, pq *pqAttempt
|
||||
return 0, errors.New("failed to generate unique localIndexId")
|
||||
}
|
||||
|
||||
// abandonPQ drops a failed PQ attempt, leaving classical attempts only. The
|
||||
// caller must hold hh.Lock.
|
||||
func (hm *HandshakeManager) abandonPQ(hh *HandshakeHostInfo) {
|
||||
hm.releasePQIndex(hh, hh.pq)
|
||||
hh.pq = nil
|
||||
hh.noPQ = true
|
||||
}
|
||||
|
||||
func (hm *HandshakeManager) releasePQIndex(hh *HandshakeHostInfo, pq *pqAttempt) {
|
||||
hm.Lock()
|
||||
defer hm.Unlock()
|
||||
@@ -314,10 +432,23 @@ func (hm *HandshakeManager) handleFragment(via ViaSender, packet []byte, h *head
|
||||
|
||||
switch h.MessageCounter {
|
||||
case 1:
|
||||
if !hm.pqConfig().accept {
|
||||
cfg := hm.pqConfig()
|
||||
if !cfg.accept {
|
||||
hm.l.Debug("dropping post-quantum handshake, not accepting them", "from", via)
|
||||
return
|
||||
}
|
||||
mine, hasV3 := hm.f.pki.getCertState().hybridSubtype()
|
||||
switch {
|
||||
case !hasV3:
|
||||
hm.l.Debug("dropping hybrid handshake, no v3 certificate to answer it with", "from", via)
|
||||
return
|
||||
case h.Subtype != mine:
|
||||
// The peer's suite uses another KEM. Like a peer without PQ, it
|
||||
// falls back to classical unless either side requires PQ.
|
||||
hm.l.Debug("dropping hybrid handshake, our v3 certificate's suite uses another KEM", "from", via,
|
||||
"style", header.SubTypeName(header.Handshake, h.Subtype), "ours", header.SubTypeName(header.Handshake, mine))
|
||||
return
|
||||
}
|
||||
if h.RemoteIndex != 0 {
|
||||
hm.l.Debug("dropping stage-1 handshake with non-zero RemoteIndex",
|
||||
"from", via, "remoteIndex", h.RemoteIndex)
|
||||
@@ -326,7 +457,7 @@ func (hm *HandshakeManager) handleFragment(via ViaSender, packet []byte, h *head
|
||||
now := time.Now()
|
||||
key, src := pqFragKeyFor(via, fh.FragID)
|
||||
if hm.pqTable.Load() >= pqCookieLoad && !(fh.HasCookie() && hm.pqCookies.valid(key, fh.Cookie, now)) {
|
||||
hm.sendCookie(via, fh, key, len(packet), now)
|
||||
hm.sendCookie(via, h.Subtype, fh, key, len(packet), now)
|
||||
return
|
||||
}
|
||||
res, err := hm.pqTable.Add(key, src, now, fh, sym)
|
||||
@@ -337,24 +468,43 @@ func (hm *HandshakeManager) handleFragment(via ViaSender, packet []byte, h *head
|
||||
if res == nil {
|
||||
return
|
||||
}
|
||||
if existing := hm.pqAnswered.lookup(res.Msg, time.Now()); existing != nil {
|
||||
// Already answered: resend, rate limited, with fresh symbols.
|
||||
if existing := hm.pqAnswered.lookup(res.Hash, time.Now()); existing != nil {
|
||||
// Already answered: resend with fresh symbols on the path this copy came by.
|
||||
if msg := existing.HandshakePacket[handshakePacketStage2]; msg != nil {
|
||||
hm.sendHandshakeResponse(via, msg, existing, true, res.Received)
|
||||
}
|
||||
hm.pqTable.Answered(key, res, now)
|
||||
return
|
||||
}
|
||||
hm.beginHandshake(via, reassembled(h, res.Msg), h, res.Received)
|
||||
if res.Repeat {
|
||||
// Answered once, but long enough ago to be forgotten: start over.
|
||||
hm.pqTable.Forget(key)
|
||||
return
|
||||
}
|
||||
hm.beginHandshake(via, reassembled(h, res.Packet), h, res.Received)
|
||||
if hm.pqAnswered.lookup(res.Hash, now) != nil {
|
||||
hm.pqTable.Answered(key, res, now)
|
||||
}
|
||||
|
||||
case 2:
|
||||
if hh := hm.queryIndex(h.RemoteIndex); hh != nil {
|
||||
hm.continuePQ(via, hh, h, fh, sym)
|
||||
}
|
||||
|
||||
case 3:
|
||||
if handshake.IsHybrid(h.Subtype) {
|
||||
hm.continueHybridResponder(via, h, fh, sym)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// continuePQ collects msg2 fragments for the initiator's PQ attempt.
|
||||
// continuePQ collects msg2 fragments for the initiator's PQ attempt, one slot
|
||||
// per responder FragID, and processes the first msg2 to complete.
|
||||
func (hm *HandshakeManager) continuePQ(via ViaSender, hh *HandshakeHostInfo, h *header.H, fh fragment.Header, sym []byte) {
|
||||
if int(fh.MsgLen) > pqMaxMsgLen {
|
||||
return
|
||||
}
|
||||
|
||||
hh.Lock()
|
||||
defer hh.Unlock()
|
||||
|
||||
@@ -364,37 +514,33 @@ func (hm *HandshakeManager) continuePQ(via ViaSender, hh *HandshakeHostInfo, h *
|
||||
}
|
||||
pq.heard = true
|
||||
|
||||
if pq.msg2 == nil {
|
||||
a, err := fragment.NewAssembly(fh)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pq.msg2 = a
|
||||
}
|
||||
ready, err := pq.msg2.Add(fh, sym)
|
||||
if errors.Is(err, fragment.ErrMismatch) {
|
||||
// The responder's FragID and MsgLen never change, so this is a stray or a
|
||||
// forgery. Start over from this fragment rather than wedge.
|
||||
pq.msg2 = nil
|
||||
a := pq.slotFor(fh)
|
||||
if a == nil {
|
||||
return
|
||||
}
|
||||
ready, err := a.Add(fh, sym)
|
||||
if err != nil || !ready {
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := pq.msg2.Decode()
|
||||
pq.msg2 = nil
|
||||
pkt, err := a.Decode(make([]byte, header.Len))
|
||||
pq.dropSlot(a)
|
||||
if err != nil {
|
||||
hm.l.Debug("failed to decode handshake fragments", "from", via, "error", err)
|
||||
return
|
||||
}
|
||||
hm.processResponse(via, hh, pq.machine, reassembled(h, msg))
|
||||
hm.processResponse(via, hh, pq.machine, reassembled(h, pkt))
|
||||
}
|
||||
|
||||
// sendFragmented sends packets to a peer: now immediately and later after the
|
||||
// repair delay. It returns the first error from the immediate sends; errors from
|
||||
// delayed sends are only logged.
|
||||
func (hm *HandshakeManager) sendFragmented(now, later [][]byte, send func([]byte) error) error {
|
||||
return hm.sendFragmentedAfter(now, later, send, hm.pqConfig().repairDelay)
|
||||
}
|
||||
|
||||
// sendFragmentedAfter is sendFragmented with the given repair delay.
|
||||
func (hm *HandshakeManager) sendFragmentedAfter(now, later [][]byte, send func([]byte) error, delay time.Duration) error {
|
||||
var first error
|
||||
for _, p := range now {
|
||||
if err := send(p); err != nil && first == nil {
|
||||
@@ -408,7 +554,6 @@ func (hm *HandshakeManager) sendFragmented(now, later [][]byte, send func([]byte
|
||||
}
|
||||
}
|
||||
}
|
||||
delay := hm.pqConfig().repairDelay
|
||||
switch {
|
||||
case len(later) == 0:
|
||||
case delay <= 0:
|
||||
@@ -419,22 +564,15 @@ func (hm *HandshakeManager) sendFragmented(now, later [][]byte, send func([]byte
|
||||
return first
|
||||
}
|
||||
|
||||
// sendFragmentedResponse sends the responder's msg2 as fragments. A resend of a
|
||||
// cached response (cached) offers fresh symbols and is rate limited to one per
|
||||
// retry interval. received is how many bytes the triggering msg1 took, which
|
||||
// bounds what may be sent back before the address is validated.
|
||||
func (hm *HandshakeManager) sendFragmentedResponse(via ViaSender, msg []byte, hostinfo *HostInfo, cached bool, received int) error {
|
||||
now := time.Now()
|
||||
if cached {
|
||||
last := hostinfo.handshakeResendAt.Load()
|
||||
if now.UnixNano()-last < int64(hm.config.tryInterval) ||
|
||||
!hostinfo.handshakeResendAt.CompareAndSwap(last, now.UnixNano()) {
|
||||
return errors.New("handshake response resend rate limited")
|
||||
}
|
||||
} else {
|
||||
hostinfo.handshakeResendAt.Store(now.UnixNano())
|
||||
}
|
||||
|
||||
// sendFragmentedResponse sends the responder's msg2 as fragments, each send
|
||||
// offering symbols the hostinfo has not sent before. The clock on resends is
|
||||
// per path and lives in the fragment table: a copy of msg1 arriving by a second
|
||||
// path (the other address family, a relay) is answered on that path at once,
|
||||
// which carries the handshake when the first path only works one way, and a
|
||||
// retry on a path is reported as a repeat at most once per retry interval.
|
||||
// received is how many bytes the triggering msg1 took, which bounds what may be
|
||||
// sent back before the address is validated.
|
||||
func (hm *HandshakeManager) sendFragmentedResponse(via ViaSender, msg []byte, hostinfo *HostInfo, received int) error {
|
||||
var h header.H
|
||||
if err := h.Parse(msg); err != nil {
|
||||
return err
|
||||
@@ -477,7 +615,7 @@ func (hm *HandshakeManager) sendFragmentedResponse(via ViaSender, msg []byte, ho
|
||||
|
||||
// notePQPeer remembers peers that completed a PQ handshake, for sticky mode.
|
||||
func (hm *HandshakeManager) notePQPeer(subtype header.MessageSubType, vpnAddrs []netip.Addr) {
|
||||
if !hm.pqConfig().sticky || subtype != pqSubtype {
|
||||
if !hm.pqConfig().sticky || !header.IsFragmented(subtype) {
|
||||
return
|
||||
}
|
||||
for _, a := range vpnAddrs {
|
||||
@@ -523,10 +661,11 @@ func (a *pqAnswered) add(msg1 []byte, hostinfo *HostInfo, now time.Time) {
|
||||
a.entries[sha256.Sum256(msg1)] = pqAnsweredEntry{hostinfo: hostinfo, at: now}
|
||||
}
|
||||
|
||||
func (a *pqAnswered) lookup(msg1 []byte, now time.Time) *HostInfo {
|
||||
// lookup finds the hostinfo that answered the msg1 with this sha256.
|
||||
func (a *pqAnswered) lookup(hash [sha256.Size]byte, now time.Time) *HostInfo {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
e, ok := a.entries[sha256.Sum256(msg1)]
|
||||
e, ok := a.entries[hash]
|
||||
if !ok || now.Sub(e.at) > a.ttl {
|
||||
return nil
|
||||
}
|
||||
@@ -625,7 +764,7 @@ func (c *pqCookies) valid(key pqFragKey, cookie fragment.Cookie, now time.Time)
|
||||
// sendCookie answers a msg1 fragment that arrived without a valid cookie while
|
||||
// under load. The reply is never larger than what triggered it, and replies are
|
||||
// rate limited as a whole.
|
||||
func (hm *HandshakeManager) sendCookie(via ViaSender, fh fragment.Header, key pqFragKey, received int, now time.Time) {
|
||||
func (hm *HandshakeManager) sendCookie(via ViaSender, subtype header.MessageSubType, fh fragment.Header, key pqFragKey, received int, now time.Time) {
|
||||
if received < pqCookieReplyLen {
|
||||
return
|
||||
}
|
||||
@@ -634,9 +773,9 @@ func (hm *HandshakeManager) sendCookie(via ViaSender, fh fragment.Header, key pq
|
||||
}
|
||||
c := hm.pqCookies.make(key, now)
|
||||
reply := make([]byte, header.Len, pqCookieReplyLen)
|
||||
header.Encode(reply, header.Version, header.Handshake, pqSubtype, fh.FragID, pqCookieCounter)
|
||||
header.Encode(reply, header.Version, header.Handshake, subtype, fh.FragID, pqCookieCounter)
|
||||
reply = append(reply, c[:]...)
|
||||
hm.f.messageMetrics.Tx(header.Handshake, pqSubtype, 1)
|
||||
hm.f.messageMetrics.Tx(header.Handshake, subtype, 1)
|
||||
if err := hm.sendTo(via)(reply); err != nil {
|
||||
hm.l.Debug("Failed to send handshake cookie", "to", via, "error", err)
|
||||
}
|
||||
@@ -674,7 +813,7 @@ func (hm *HandshakeManager) handleCookie(via ViaSender, packet []byte, h *header
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hm.messageMetrics.Tx(header.Handshake, pqSubtype, int64(len(pkts)+len(later)))
|
||||
hm.messageMetrics.Tx(header.Handshake, pq.subtype, int64(len(pkts)+len(later)))
|
||||
if err := hm.sendFragmented(pkts, later, hm.sendTo(via)); err != nil {
|
||||
hm.l.Debug("Failed to resend handshake with cookie", "to", via, "error", err)
|
||||
}
|
||||
@@ -693,7 +832,7 @@ func (hm *HandshakeManager) sendTo(via ViaSender) func([]byte) error {
|
||||
if via.relay == nil {
|
||||
return errors.New("both addr and via.relay are nil")
|
||||
}
|
||||
f.SendVia(via.relayHI, via.relay, p, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||
f.sendHandshakeVia(via.relayHI, via.relay, p)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
+226
-30
@@ -1,12 +1,15 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"math/rand/v2"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake/fragment"
|
||||
"github.com/slackhq/nebula/header"
|
||||
@@ -48,11 +51,26 @@ func newPQTestManager(t *testing.T) (*HandshakeManager, *recordingConn) {
|
||||
handshakeManager: hm,
|
||||
outside: conn,
|
||||
messageMetrics: newMessageMetricsOnlyRecvError(),
|
||||
pki: newV3TestPKI(t),
|
||||
l: l,
|
||||
}
|
||||
return hm, conn
|
||||
}
|
||||
|
||||
// newV3TestPKI holds a version 3 certificate, which post-quantum handshakes need.
|
||||
func newV3TestPKI(t *testing.T) *PKI {
|
||||
t.Helper()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version3, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
c, _, keyPEM, _ := cert_test.NewTestCert(cert.Version3, cert.Curve_CURVE25519, ca, caKey, "me", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}, nil, nil)
|
||||
key, _, curve, err := cert.UnmarshalPrivateKeyFromPEM(keyPEM)
|
||||
require.NoError(t, err)
|
||||
cs, err := newCertState(cert.Version2, nil, cert.V2Form(c), c, false, curve, key, "aes")
|
||||
require.NoError(t, err)
|
||||
p := &PKI{}
|
||||
p.cs.Store(cs)
|
||||
return p
|
||||
}
|
||||
|
||||
// fragmentIndexes checks every packet is a fragment of the expected response and
|
||||
// returns their symbol indexes.
|
||||
func fragmentIndexes(t *testing.T, pkts [][]byte, fragID, remoteIndex uint32) []int {
|
||||
@@ -62,7 +80,7 @@ func fragmentIndexes(t *testing.T, pkts [][]byte, fragID, remoteIndex uint32) []
|
||||
require.LessOrEqual(t, len(p), fragment.MaxPacketLen)
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(p))
|
||||
assert.Equal(t, pqSubtype, h.Subtype)
|
||||
assert.Equal(t, header.HandshakeIXHybridMLKEM1024, h.Subtype)
|
||||
assert.Equal(t, remoteIndex, h.RemoteIndex)
|
||||
assert.Equal(t, uint64(2), h.MessageCounter)
|
||||
fh, _, err := fragment.Parse(p[header.Len:])
|
||||
@@ -80,7 +98,7 @@ func TestSendFragmentedResponse(t *testing.T) {
|
||||
|
||||
// A 2000 byte message is 2 symbols of 1000, so packets of 1024 bytes.
|
||||
msg := make([]byte, header.Len, header.Len+2000)
|
||||
header.Encode(msg, header.Version, header.Handshake, pqSubtype, 5, 2)
|
||||
header.Encode(msg, header.Version, header.Handshake, header.HandshakeIXHybridMLKEM1024, 5, 2)
|
||||
r := rand.New(rand.NewPCG(1, 1))
|
||||
for range 2000 {
|
||||
msg = append(msg, byte(r.Uint32()))
|
||||
@@ -88,35 +106,25 @@ func TestSendFragmentedResponse(t *testing.T) {
|
||||
const pktLen = header.Len + fragment.HeaderLen + 1000
|
||||
|
||||
t.Run("first send", func(t *testing.T) {
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, false, 0))
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, 0))
|
||||
assert.Equal(t, []int{0, 1, 2, 3}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("resends are rate limited", func(t *testing.T) {
|
||||
require.Error(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, 10*pktLen))
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
|
||||
allowResend := func() {
|
||||
hostinfo.handshakeResendAt.Store(time.Now().Add(-time.Second).UnixNano())
|
||||
}
|
||||
|
||||
t.Run("resend offers fresh symbols", func(t *testing.T) {
|
||||
allowResend()
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, 10*pktLen))
|
||||
t.Run("a repeat is answered at once with fresh symbols", func(t *testing.T) {
|
||||
// No clock gates a resend: a repeat already cost the initiator K fresh
|
||||
// symbols on that path, and the amplification budget bounds the answer.
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, 10*pktLen))
|
||||
assert.Equal(t, []int{4, 5, 6, 7}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("amplification budget trims repair", func(t *testing.T) {
|
||||
allowResend()
|
||||
// 3x of a little over one packet allows 3 packets: both data and 1 repair.
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, pktLen+10))
|
||||
require.NoError(t, hm.sendFragmentedResponse(via, msg, hostinfo, pktLen+10))
|
||||
assert.Equal(t, []int{8, 9, 10}, fragmentIndexes(t, conn.take(), 77, 5))
|
||||
})
|
||||
|
||||
t.Run("amplification budget below the data refuses", func(t *testing.T) {
|
||||
allowResend()
|
||||
require.Error(t, hm.sendFragmentedResponse(via, msg, hostinfo, true, pktLen/2))
|
||||
require.Error(t, hm.sendFragmentedResponse(via, msg, hostinfo, pktLen/2))
|
||||
assert.Empty(t, conn.take())
|
||||
})
|
||||
}
|
||||
@@ -126,11 +134,11 @@ func TestPQAnswered(t *testing.T) {
|
||||
a := newPQAnswered(5 * time.Second)
|
||||
hi := &HostInfo{}
|
||||
|
||||
assert.Nil(t, a.lookup([]byte("msg1"), now))
|
||||
assert.Nil(t, a.lookup(sha256.Sum256([]byte("msg1")), now))
|
||||
a.add([]byte("msg1"), hi, now)
|
||||
assert.Same(t, hi, a.lookup([]byte("msg1"), now.Add(time.Second)))
|
||||
assert.Nil(t, a.lookup([]byte("other"), now))
|
||||
assert.Nil(t, a.lookup([]byte("msg1"), now.Add(6*time.Second)), "stale entries are not answered")
|
||||
assert.Same(t, hi, a.lookup(sha256.Sum256([]byte("msg1")), now.Add(time.Second)))
|
||||
assert.Nil(t, a.lookup(sha256.Sum256([]byte("other")), now))
|
||||
assert.Nil(t, a.lookup(sha256.Sum256([]byte("msg1")), now.Add(6*time.Second)), "stale entries are not answered")
|
||||
|
||||
a.expire(now.Add(6 * time.Second))
|
||||
assert.Empty(t, a.entries)
|
||||
@@ -183,7 +191,7 @@ func TestPQCookies(t *testing.T) {
|
||||
// pqMsg1Fragment builds the first fragment of a msg1, optionally with a cookie.
|
||||
func pqMsg1Fragment(t *testing.T, fragID uint32, cookie *fragment.Cookie) ([]byte, *header.H) {
|
||||
t.Helper()
|
||||
s, err := fragment.NewSender(make([]byte, 2000), pqSubtype, 0, 1, fragID)
|
||||
s, err := fragment.NewSender(make([]byte, 2000), header.HandshakeIXHybridMLKEM1024, 0, 1, fragID)
|
||||
require.NoError(t, err)
|
||||
if cookie != nil {
|
||||
s.SetCookie(*cookie)
|
||||
@@ -238,7 +246,7 @@ func TestPQCookieUnderLoad(t *testing.T) {
|
||||
var rh header.H
|
||||
require.NoError(t, rh.Parse(reply))
|
||||
assert.Equal(t, header.Handshake, rh.Type)
|
||||
assert.Equal(t, pqSubtype, rh.Subtype)
|
||||
assert.Equal(t, header.HandshakeIXHybridMLKEM1024, rh.Subtype)
|
||||
assert.Equal(t, uint32(7), rh.RemoteIndex, "the reply names the initiator's FragID")
|
||||
assert.Equal(t, uint64(pqCookieCounter), rh.MessageCounter)
|
||||
copy(cookie[:], reply[header.Len:])
|
||||
@@ -270,7 +278,7 @@ func TestPQCookieUnderLoad(t *testing.T) {
|
||||
|
||||
t.Run("a reply never outgrows what prompted it", func(t *testing.T) {
|
||||
p, h := pqMsg1Fragment(t, 8, nil)
|
||||
hm.sendCookie(via, fragment.Header{FragID: 8}, pqFragKey{}, pqCookieReplyLen-1, time.Now())
|
||||
hm.sendCookie(via, header.HandshakeIXHybridMLKEM1024, fragment.Header{FragID: 8}, pqFragKey{}, pqCookieReplyLen-1, time.Now())
|
||||
assert.Empty(t, conn.take())
|
||||
hm.handleFragment(via, p, h)
|
||||
assert.Len(t, conn.take(), 1)
|
||||
@@ -281,7 +289,7 @@ func TestPQHandleCookie(t *testing.T) {
|
||||
hm, conn := newPQTestManager(t)
|
||||
via := ViaSender{UdpAddr: netip.MustParseAddrPort("192.0.2.1:4242")}
|
||||
|
||||
s, err := fragment.NewSender(make([]byte, 2000), pqSubtype, 0, 1, 99)
|
||||
s, err := fragment.NewSender(make([]byte, 2000), header.HandshakeIXHybridMLKEM1024, 0, 1, 99)
|
||||
require.NoError(t, err)
|
||||
_, _, err = s.Attempt(2)
|
||||
require.NoError(t, err)
|
||||
@@ -289,7 +297,7 @@ func TestPQHandleCookie(t *testing.T) {
|
||||
hm.indexes[99] = hh
|
||||
|
||||
reply := make([]byte, header.Len, pqCookieReplyLen)
|
||||
header.Encode(reply, header.Version, header.Handshake, pqSubtype, 99, pqCookieCounter)
|
||||
header.Encode(reply, header.Version, header.Handshake, header.HandshakeIXHybridMLKEM1024, 99, pqCookieCounter)
|
||||
reply = append(reply, bytes16(0xab)...)
|
||||
var h header.H
|
||||
require.NoError(t, h.Parse(reply))
|
||||
@@ -311,7 +319,7 @@ func TestPQHandleCookie(t *testing.T) {
|
||||
|
||||
t.Run("replies for other indexes are ignored", func(t *testing.T) {
|
||||
other := append([]byte(nil), reply...)
|
||||
header.Encode(other, header.Version, header.Handshake, pqSubtype, 98, pqCookieCounter)
|
||||
header.Encode(other, header.Version, header.Handshake, header.HandshakeIXHybridMLKEM1024, 98, pqCookieCounter)
|
||||
var oh header.H
|
||||
require.NoError(t, oh.Parse(other))
|
||||
hh.pq.cookieResendAt = time.Time{}
|
||||
@@ -335,6 +343,7 @@ func TestReloadPQ(t *testing.T) {
|
||||
cfg := defaultHandshakeConfig
|
||||
cfg.pq = pqHandshakeConfigFrom(c)
|
||||
hm := NewHandshakeManager(l, newHostMap(l), newTestLighthouse(), &udp.NoopConn{}, cfg)
|
||||
hm.f = &Interface{pki: newV3TestPKI(t)}
|
||||
c.RegisterReloadCallback(hm.reloadPQ)
|
||||
|
||||
assert.Equal(t, pqHandshakeConfig{repairDelay: DefaultPQRepairDelay}, *hm.pqConfig())
|
||||
@@ -393,6 +402,193 @@ func TestUsePQ(t *testing.T) {
|
||||
|
||||
set(pqHandshakeConfig{initiate: true, sticky: true})
|
||||
assert.Equal(t, []bool{true, false}, attempts(false, false), "sticky alternates until the peer has done PQ")
|
||||
hm.notePQPeer(pqSubtype, []netip.Addr{peer})
|
||||
hm.notePQPeer(header.HandshakeIXHybridMLKEM1024, []netip.Addr{peer})
|
||||
assert.Equal(t, []bool{true, true, true}, attempts(false, false, false), "then only PQ")
|
||||
}
|
||||
|
||||
// msg2Fragments returns one attempt's packets carrying msg as a responder's msg2
|
||||
// under fragID, data symbols first and then repair.
|
||||
func msg2Fragments(t *testing.T, msg []byte, fragID uint32) [][]byte {
|
||||
t.Helper()
|
||||
s, err := fragment.NewSender(msg, header.HandshakeIXHybridMLKEM1024, 7, 2, fragID)
|
||||
require.NoError(t, err)
|
||||
now, later, err := s.Attempt(fragment.DefaultRepair(s.Layout().K))
|
||||
require.NoError(t, err)
|
||||
return append(now, later...)
|
||||
}
|
||||
|
||||
// feedMsg2 puts one packet through an attempt's slots.
|
||||
func feedMsg2(t *testing.T, pq *pqAttempt, p []byte) (*fragment.Assembly, fragment.Header, bool) {
|
||||
t.Helper()
|
||||
fh, sym, err := fragment.Parse(p[header.Len:])
|
||||
require.NoError(t, err)
|
||||
a := pq.slotFor(fh)
|
||||
require.NotNil(t, a)
|
||||
ready, err := a.Add(fh, sym)
|
||||
require.NoError(t, err)
|
||||
return a, fh, ready
|
||||
}
|
||||
|
||||
func slotsUsed(pq *pqAttempt) (n int, ids []uint32) {
|
||||
for _, s := range pq.msg2 {
|
||||
if s.a != nil {
|
||||
n++
|
||||
ids = append(ids, s.fragID)
|
||||
}
|
||||
}
|
||||
return n, ids
|
||||
}
|
||||
|
||||
// TestPQMsg2Slots interleaves two responders' msg2 bursts, the shape two hosts
|
||||
// answering the same msg1 produce on a LAN, and checks each fills its own slot.
|
||||
func TestPQMsg2Slots(t *testing.T) {
|
||||
msgB := make([]byte, 9625) // the hybrid msg2: k = 9
|
||||
msgC := make([]byte, 9625)
|
||||
for i := range msgB {
|
||||
msgB[i], msgC[i] = 'b', 'c'
|
||||
}
|
||||
pktsB := msg2Fragments(t, msgB, 1001)
|
||||
pktsC := msg2Fragments(t, msgC, 2002)
|
||||
require.Len(t, pktsB, 12)
|
||||
|
||||
// B0 B1 C0 B2 B3 B4 C1 C2 B5 B6 B7 B8 C3: no run of one FragID reaches nine,
|
||||
// so a single slot emptied on every change would never complete.
|
||||
order := []struct {
|
||||
fromC bool
|
||||
i int
|
||||
}{{false, 0}, {false, 1}, {true, 0}, {false, 2}, {false, 3}, {false, 4}, {true, 1}, {true, 2}, {false, 5}, {false, 6}, {false, 7}, {false, 8}, {true, 3}}
|
||||
|
||||
pq := &pqAttempt{}
|
||||
var got []byte
|
||||
for n, o := range order {
|
||||
p := pktsB[o.i]
|
||||
if o.fromC {
|
||||
p = pktsC[o.i]
|
||||
}
|
||||
a, _, ready := feedMsg2(t, pq, p)
|
||||
if !ready {
|
||||
continue
|
||||
}
|
||||
require.Equal(t, 11, n, "B completes on its ninth symbol")
|
||||
msg, err := a.Decode(nil)
|
||||
require.NoError(t, err)
|
||||
got = msg
|
||||
pq.dropSlot(a)
|
||||
}
|
||||
require.Equal(t, msgB, got)
|
||||
|
||||
n, ids := slotsUsed(pq)
|
||||
assert.Equal(t, 1, n)
|
||||
assert.Equal(t, []uint32{2002}, ids, "B's slot was released, C's kept")
|
||||
|
||||
// C's four symbols survived B's completion, so five more finish it.
|
||||
var c *fragment.Assembly
|
||||
var ready bool
|
||||
for i := 4; i < 9; i++ {
|
||||
c, _, ready = feedMsg2(t, pq, pktsC[i])
|
||||
assert.Equal(t, i == 8, ready, "symbol %d", i)
|
||||
}
|
||||
msg, err := c.Decode(nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, msgC, msg)
|
||||
|
||||
t.Run("a third responder takes the slot holding the least", func(t *testing.T) {
|
||||
pq := &pqAttempt{}
|
||||
feedMsg2(t, pq, pktsB[0])
|
||||
feedMsg2(t, pq, pktsB[1])
|
||||
feedMsg2(t, pq, pktsC[0])
|
||||
pktsD := msg2Fragments(t, msgC, 3003)
|
||||
d, fh, _ := feedMsg2(t, pq, pktsD[0])
|
||||
_, ids := slotsUsed(pq)
|
||||
assert.ElementsMatch(t, []uint32{1001, 3003}, ids)
|
||||
|
||||
l, err := fh.Layout()
|
||||
require.NoError(t, err)
|
||||
b, _, _ := feedMsg2(t, pq, pktsB[2])
|
||||
assert.Equal(t, 3*l.SymbolSize, b.Stored(), "B kept its symbols")
|
||||
assert.Equal(t, l.SymbolSize, d.Stored())
|
||||
})
|
||||
|
||||
t.Run("a different MsgLen under the same FragID starts the slot over", func(t *testing.T) {
|
||||
pq := &pqAttempt{}
|
||||
feedMsg2(t, pq, pktsB[0])
|
||||
feedMsg2(t, pq, pktsB[1])
|
||||
shorter := msg2Fragments(t, msgB[:9000], 1001)
|
||||
a, fh, _ := feedMsg2(t, pq, shorter[0])
|
||||
l, err := fh.Layout()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, l.SymbolSize, a.Stored())
|
||||
n, ids := slotsUsed(pq)
|
||||
assert.Equal(t, 1, n)
|
||||
assert.Equal(t, []uint32{1001}, ids)
|
||||
})
|
||||
|
||||
t.Run("an oversize claim is dropped before it takes a slot", func(t *testing.T) {
|
||||
hm, _ := newPQTestManager(t)
|
||||
hh := &HandshakeHostInfo{hostinfo: &HostInfo{}, pq: &pqAttempt{index: 42}}
|
||||
hm.indexes[42] = hh
|
||||
fh := fragment.Header{FragID: 1001, MsgLen: pqMaxMsgLen + 1}
|
||||
l, err := fh.Layout()
|
||||
require.NoError(t, err)
|
||||
hm.continuePQ(ViaSender{}, hh, &header.H{RemoteIndex: 42, MessageCounter: 2}, fh, make([]byte, l.SymbolSize))
|
||||
n, _ := slotsUsed(hh.pq)
|
||||
assert.Zero(t, n)
|
||||
assert.False(t, hh.pq.heard)
|
||||
})
|
||||
}
|
||||
|
||||
// Post-quantum handshakes are hybrid only, so without a version 3 certificate
|
||||
// there is nothing to initiate and require is refused.
|
||||
func TestPQNeedsV3(t *testing.T) {
|
||||
l := test.NewLogger()
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
c2, _, keyPEM, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "me", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}, nil, nil)
|
||||
key, _, curve, err := cert.UnmarshalPrivateKeyFromPEM(keyPEM)
|
||||
require.NoError(t, err)
|
||||
cs, err := newCertState(cert.Version2, nil, c2, nil, false, curve, key, "aes")
|
||||
require.NoError(t, err)
|
||||
v2PKI := &PKI{}
|
||||
v2PKI.cs.Store(cs)
|
||||
|
||||
hm := NewHandshakeManager(l, newHostMap(l), newTestLighthouse(), &udp.NoopConn{}, defaultHandshakeConfig)
|
||||
hm.f = &Interface{pki: v2PKI}
|
||||
hm.pq.Store(&pqHandshakeConfig{initiate: true, accept: true})
|
||||
assert.False(t, hm.usePQ(&HandshakeHostInfo{counter: 1}, netip.MustParseAddr("10.0.0.2"), false), "no v3 certificate, no hybrid attempt")
|
||||
|
||||
conf := config.NewC(l)
|
||||
require.NoError(t, conf.LoadString(`handshakes: {pq: {initiate: true}}`))
|
||||
conf.RegisterReloadCallback(hm.reloadPQ)
|
||||
require.NoError(t, conf.ReloadConfigString(`handshakes: {pq: {require: true}}`))
|
||||
assert.False(t, hm.pqConfig().require, "require without a v3 certificate is refused on reload")
|
||||
|
||||
// And when loading the pki.
|
||||
certPEM, err := c2.MarshalPEM()
|
||||
require.NoError(t, err)
|
||||
conf = config.NewC(l)
|
||||
conf.Settings["pki"] = map[string]any{"cert": string(certPEM), "key": string(keyPEM)}
|
||||
conf.Settings["handshakes"] = map[string]any{"pq": map[string]any{"require": true}}
|
||||
_, err = newCertStateFromConfig(conf, "aes")
|
||||
require.ErrorContains(t, err, "handshakes.pq.require needs a version 3 certificate")
|
||||
}
|
||||
|
||||
// After answering a peer's hybrid msg1, its classical msg1s go unanswered for
|
||||
// four retry intervals, and only for that peer.
|
||||
func TestHybridCrossingWindow(t *testing.T) {
|
||||
hm, _ := newPQTestManager(t)
|
||||
peer := []netip.Addr{netip.MustParseAddr("10.1.0.1")}
|
||||
other := []netip.Addr{netip.MustParseAddr("10.1.0.2")}
|
||||
now := time.Unix(1000, 0)
|
||||
w := 4 * hm.config.tryInterval
|
||||
assert.Equal(t, w, hm.hybridWindow())
|
||||
|
||||
assert.False(t, hm.crossesHybrid(peer, now))
|
||||
hm.noteHybridMsg1(peer, now)
|
||||
assert.True(t, hm.crossesHybrid(peer, now.Add(w-time.Millisecond)))
|
||||
assert.False(t, hm.crossesHybrid(peer, now.Add(w)))
|
||||
assert.False(t, hm.crossesHybrid(other, now))
|
||||
|
||||
hm.expireHybridResponders(now.Add(w))
|
||||
hm.hybrid.answeredMu.Lock()
|
||||
assert.Empty(t, hm.hybrid.answered, "expired windows are forgotten")
|
||||
hm.hybrid.answeredMu.Unlock()
|
||||
}
|
||||
+11
-8
@@ -68,16 +68,19 @@ const (
|
||||
HandshakeIXPSK0 MessageSubType = 0
|
||||
HandshakeXXPSK0 MessageSubType = 1
|
||||
|
||||
// HandshakeIXPSK2MLKEM1024 is IX with an ephemeral ML-KEM-1024 exchange mixed
|
||||
// in through the psk2 slot. Its messages exceed the MTU and travel as
|
||||
// fragments (see handshake/fragment).
|
||||
HandshakeIXPSK2MLKEM1024 MessageSubType = 2
|
||||
// 2 was ix_psk2_mlkem1024, an ephemeral ML-KEM exchange over IX on version 2
|
||||
// certificates that was never released. Do not reuse it.
|
||||
|
||||
// HandshakeIXHybridMLKEM1024 is the hybrid IX of github.com/DefinedNet/noise:
|
||||
// IX with X25519 or P256 and ML-KEM-1024 side by side, authenticated by
|
||||
// version 3 certificates. It takes three messages and travels as fragments.
|
||||
HandshakeIXHybridMLKEM1024 MessageSubType = 3
|
||||
)
|
||||
|
||||
// IsFragmented reports whether handshake messages of this subtype travel as
|
||||
// fragments.
|
||||
func IsFragmented(st MessageSubType) bool {
|
||||
return st == HandshakeIXPSK2MLKEM1024
|
||||
return st == HandshakeIXHybridMLKEM1024
|
||||
}
|
||||
|
||||
var ErrHeaderTooShort = errors.New("header is too short")
|
||||
@@ -99,8 +102,8 @@ var subTypeMap = map[MessageType]*map[MessageSubType]string{
|
||||
Test: &subTypeTestMap,
|
||||
CloseTunnel: &subTypeNoneMap,
|
||||
Handshake: {
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK2MLKEM1024: "ix_psk2_mlkem1024",
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXHybridMLKEM1024: "ix_hybrid_mlkem1024",
|
||||
},
|
||||
Control: &subTypeNoneMap,
|
||||
}
|
||||
@@ -211,7 +214,7 @@ func IsValidSubType(t MessageType, s MessageSubType) bool {
|
||||
case Message:
|
||||
return s == MessageNone || s == MessageRelay
|
||||
case Handshake:
|
||||
return s == HandshakeIXPSK0 || s == HandshakeIXPSK2MLKEM1024
|
||||
return s == HandshakeIXPSK0 || s == HandshakeIXHybridMLKEM1024
|
||||
case Test:
|
||||
return s == TestReply || s == TestRequest
|
||||
case Control, CloseTunnel, RecvError, LightHouse:
|
||||
|
||||
@@ -96,8 +96,8 @@ func TestTypeMap(t *testing.T) {
|
||||
Test: &subTypeTestMap,
|
||||
CloseTunnel: &subTypeNoneMap,
|
||||
Handshake: {
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXPSK2MLKEM1024: "ix_psk2_mlkem1024",
|
||||
HandshakeIXPSK0: "ix_psk0",
|
||||
HandshakeIXHybridMLKEM1024: "ix_hybrid_mlkem1024",
|
||||
},
|
||||
Control: &subTypeNoneMap,
|
||||
}, subTypeMap)
|
||||
@@ -123,7 +123,9 @@ func TestIsValidSubType(t *testing.T) {
|
||||
assert.False(t, IsValidSubType(Message, 2))
|
||||
|
||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXPSK0))
|
||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXPSK2MLKEM1024))
|
||||
assert.True(t, IsValidSubType(Handshake, HandshakeIXHybridMLKEM1024))
|
||||
// 2 was the unreleased ix_psk2_mlkem1024 and stays reserved.
|
||||
assert.False(t, IsValidSubType(Handshake, 2))
|
||||
// HandshakeXXPSK0 is defined but not a wire-valid subtype.
|
||||
assert.False(t, IsValidSubType(Handshake, HandshakeXXPSK0))
|
||||
|
||||
|
||||
+3
-2
@@ -261,8 +261,9 @@ type HostInfo struct {
|
||||
HandshakePacket map[uint8][]byte
|
||||
|
||||
// A responder resending a fragmented handshake response offers symbols it has
|
||||
// not sent before, at most once per retry interval.
|
||||
handshakeResendAt atomic.Int64 // unix nanos of the last send
|
||||
// not sent before. Once complete, a hybrid responder confirms again for a
|
||||
// resent msg3 at most once per retry interval.
|
||||
handshakeResendAt atomic.Int64 // unix nanos of the last confirmation
|
||||
handshakeNextSymbol atomic.Uint32 // next fragment symbol index to offer
|
||||
|
||||
// nextLHQuery is the earliest we can ask the lighthouse for new information.
|
||||
|
||||
+2
-2
@@ -839,7 +839,7 @@ func (lh *LightHouse) innerQueryServer(addr netip.Addr, nb, out []byte) {
|
||||
for _, lhVpnAddr := range lighthouses {
|
||||
hi := lh.ifce.GetHostInfo(lhVpnAddr)
|
||||
if hi != nil {
|
||||
v = hi.ConnectionState.myCert.Version()
|
||||
v = protocolVersion(hi.ConnectionState.myCert.Version())
|
||||
} else {
|
||||
v = lh.ifce.GetCertState().initiatingVersion
|
||||
}
|
||||
@@ -1001,7 +1001,7 @@ func (lh *LightHouse) SendUpdate() {
|
||||
var v cert.Version
|
||||
hi := lh.ifce.GetHostInfo(lhVpnAddr)
|
||||
if hi != nil {
|
||||
v = hi.ConnectionState.myCert.Version()
|
||||
v = protocolVersion(hi.ConnectionState.myCert.Version())
|
||||
} else {
|
||||
v = lh.ifce.GetCertState().initiatingVersion
|
||||
}
|
||||
|
||||
@@ -235,6 +235,7 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
pq: pqHandshakeConfigFrom(c),
|
||||
}
|
||||
|
||||
warnPQWithoutV3(l, handshakeConfig.pq, pki.getCertState())
|
||||
handshakeManager := NewHandshakeManager(l, hostMap, lightHouse, udpConns[0], handshakeConfig)
|
||||
c.RegisterReloadCallback(handshakeManager.reloadPQ)
|
||||
lightHouse.handshakeTrigger = handshakeManager.trigger
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// CipherStateAESGCM is the data-plane wrapper for the AES-GCM AEAD cipher.
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ package noiseutil
|
||||
import (
|
||||
"crypto/boring"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
var CipherAESGCM noise.CipherFunc = CipherAESGCMFIPS140
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// CipherStateChaChaPoly is the data-plane wrapper for the ChaCha20-Poly1305 AEAD cipher.
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// RejectHeadroom is the wrap gap for senders racing the counter, sized large enough for any routine count.
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
_ "crypto/tls"
|
||||
_ "unsafe"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// TODO: Use NewGCMWithCounterNonce or NewGCMForQUIC once available:
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// DHP256 is the NIST P-256 ECDH function
|
||||
|
||||
@@ -5,7 +5,7 @@ package noiseutil
|
||||
import (
|
||||
"crypto/fips140"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// EncryptLockNeeded indicates if calls to Encrypt need a lock
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import (
|
||||
|
||||
"github.com/slackhq/nebula/pkclient"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
)
|
||||
|
||||
// DHP256PKCS11 is the NIST P-256 ECDH function
|
||||
|
||||
+3
-1
@@ -101,7 +101,9 @@ func (f *Interface) readOutsidePackets(via ViaSender, packet []byte, rxc *rxCont
|
||||
// At this point we should have a valid existing tunnel, verify and send
|
||||
// recvError if necessary
|
||||
if hostinfo == nil || hostinfo.ConnectionState == nil {
|
||||
if !via.IsRelayed {
|
||||
// A hybrid responder waiting for msg3 already gets data from an initiator
|
||||
// that has its keys. A RecvError would tear that new tunnel down.
|
||||
if !via.IsRelayed && !f.handshakeManager.isHybridResponder(h.RemoteIndex) {
|
||||
f.maybeSendRecvError(via.UdpAddr, h.RemoteIndex)
|
||||
}
|
||||
return
|
||||
|
||||
@@ -16,11 +16,12 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/DefinedNet/noise"
|
||||
"github.com/gaissmai/bart"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/util"
|
||||
)
|
||||
@@ -38,6 +39,11 @@ type CertState struct {
|
||||
v2Cert cert.Certificate
|
||||
v2Credential *handshake.Credential
|
||||
|
||||
// v3Cert, when present, is what v2Cert is the v2 form of. It is only used by
|
||||
// hybrid handshakes, every other handshake presents v2Cert.
|
||||
v3Cert cert.Certificate
|
||||
v3Credential *handshake.Credential
|
||||
|
||||
initiatingVersion cert.Version
|
||||
privateKey []byte
|
||||
pkcs11Backed bool
|
||||
@@ -216,6 +222,15 @@ func (cs *CertState) GetDefaultCertificate() cert.Certificate {
|
||||
// DefaultVersion returns the preferred cert version for initiating handshakes.
|
||||
func (cs *CertState) DefaultVersion() cert.Version { return cs.initiatingVersion }
|
||||
|
||||
// hybridSubtype returns the hybrid handshake subtype for the KEM of the v3
|
||||
// certificate's suite, false without a v3 certificate.
|
||||
func (cs *CertState) hybridSubtype() (header.MessageSubType, bool) {
|
||||
if cs.v3Cert == nil {
|
||||
return 0, false
|
||||
}
|
||||
return handshake.HybridSubtype(cert.PQSuiteOf(cs.v3Cert))
|
||||
}
|
||||
|
||||
// GetCredential returns the pre-computed handshake credential for the given version, or nil.
|
||||
func (cs *CertState) GetCredential(v cert.Version) *handshake.Credential {
|
||||
switch v {
|
||||
@@ -223,6 +238,8 @@ func (cs *CertState) GetCredential(v cert.Version) *handshake.Credential {
|
||||
return cs.v1Credential
|
||||
case cert.Version2:
|
||||
return cs.v2Credential
|
||||
case cert.Version3:
|
||||
return cs.v3Credential
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -233,11 +250,23 @@ func (cs *CertState) getCertificate(v cert.Version) cert.Certificate {
|
||||
return cs.v1Cert
|
||||
case cert.Version2:
|
||||
return cs.v2Cert
|
||||
case cert.Version3:
|
||||
return cs.v3Cert
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// protocolVersion is the version of the messages spoken over a tunnel built on a
|
||||
// certificate of version v. Version 3 only changes the handshake, everything
|
||||
// after it is version 2.
|
||||
func protocolVersion(v cert.Version) cert.Version {
|
||||
if v == cert.Version3 {
|
||||
return cert.Version2
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// newCipherSuite builds the noise.CipherSuite for the given curve and cipher.
|
||||
// When fips140Enforced is true (FIPS 140-only mode), non-approved algorithms
|
||||
// (Curve25519 and ChaChaPoly) are rejected with an error. Callers pass
|
||||
@@ -287,7 +316,14 @@ func (cs *CertState) MarshalJSON() ([]byte, error) {
|
||||
msg = append(msg, b)
|
||||
}
|
||||
|
||||
if cs.v2Cert != nil {
|
||||
// A v3 certificate shows its v2 form's fingerprint itself.
|
||||
if cs.v3Cert != nil {
|
||||
b, err := cs.v3Cert.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msg = append(msg, b)
|
||||
} else if cs.v2Cert != nil {
|
||||
b, err := cs.v2Cert.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -329,7 +365,7 @@ func newCertStateFromConfig(c *config.C, cipher string) (*CertState, error) {
|
||||
}
|
||||
}
|
||||
|
||||
var crt, v1, v2 cert.Certificate
|
||||
var crt, v1, v2, v3 cert.Certificate
|
||||
for {
|
||||
// Load the certificate
|
||||
crt, rawCert, err = loadCertificate(rawCert)
|
||||
@@ -352,6 +388,11 @@ func newCertStateFromConfig(c *config.C, cipher string) (*CertState, error) {
|
||||
return nil, fmt.Errorf("v2 certificate already found in pki.cert")
|
||||
}
|
||||
v2 = crt
|
||||
case cert.Version3:
|
||||
if v3 != nil {
|
||||
return nil, fmt.Errorf("v3 certificate already found in pki.cert")
|
||||
}
|
||||
v3 = crt
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown certificate version %v", crt.Version())
|
||||
}
|
||||
@@ -361,6 +402,25 @@ func newCertStateFromConfig(c *config.C, cipher string) (*CertState, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if v3 != nil {
|
||||
// A v3 certificate brings its own v2 form. Listing that too is fine, anything else is a mistake.
|
||||
form := cert.V2Form(v3)
|
||||
if v2 != nil {
|
||||
want, err := form.Fingerprint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
got, err := v2.Fingerprint()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if want != got {
|
||||
return nil, errors.New("the v2 certificate in pki.cert is not the v2 form of the v3 certificate")
|
||||
}
|
||||
}
|
||||
v2 = form
|
||||
}
|
||||
|
||||
if v1 == nil && v2 == nil {
|
||||
return nil, errors.New("no certificates found in pki.cert")
|
||||
}
|
||||
@@ -386,10 +446,18 @@ func newCertStateFromConfig(c *config.C, cipher string) (*CertState, error) {
|
||||
return nil, fmt.Errorf("unknown pki.initiating_version: %v", rawInitiatingVersion)
|
||||
}
|
||||
|
||||
return newCertState(initiatingVersion, v1, v2, isPkcs11, curve, rawKey, cipher)
|
||||
// Post-quantum handshakes are hybrid only, so requiring them without a v3
|
||||
// certificate would leave this node unable to reach anyone.
|
||||
if v3 == nil && c.GetBool("handshakes.pq.require", false) {
|
||||
return nil, errors.New("handshakes.pq.require needs a version 3 certificate in pki.cert")
|
||||
}
|
||||
|
||||
return newCertState(initiatingVersion, v1, v2, v3, isPkcs11, curve, rawKey, cipher)
|
||||
}
|
||||
|
||||
func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, privateKeyCurve cert.Curve, privateKey []byte, cipher string) (*CertState, error) {
|
||||
// newCertState builds the handshake credentials. v3, when present, must be what v2 is the v2 form of. privateKey is
|
||||
// then the composite key, classical || the seed of the KEM of v3's suite, and v1 and v2 get its classical half.
|
||||
func newCertState(dv cert.Version, v1, v2, v3 cert.Certificate, pkcs11backed bool, privateKeyCurve cert.Curve, privateKey []byte, cipher string) (*CertState, error) {
|
||||
cs := CertState{
|
||||
privateKey: privateKey,
|
||||
pkcs11Backed: pkcs11backed,
|
||||
@@ -415,11 +483,40 @@ func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, p
|
||||
cs.initiatingVersion = dv
|
||||
}
|
||||
|
||||
classicalKey := privateKey
|
||||
if !pkcs11backed {
|
||||
classicalKey = cert.ClassicalPrivateKey(privateKey)
|
||||
}
|
||||
|
||||
if v3 != nil {
|
||||
if pkcs11backed {
|
||||
return nil, errors.New("v3 certificates need their private key in pki.key, not a PKCS#11 token")
|
||||
}
|
||||
if err := v3.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
|
||||
return nil, fmt.Errorf("private key is not a pair with public key in v3 nebula cert: %w", err)
|
||||
}
|
||||
suite := cert.PQSuiteOf(v3)
|
||||
if _, ok := handshake.HybridSubtype(suite); !ok {
|
||||
return nil, fmt.Errorf("v3 nebula cert uses post-quantum suite %v, which no hybrid handshake supports", suite)
|
||||
}
|
||||
|
||||
v3hs, err := v3.MarshalForHandshakes()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error marshalling v3 certificate for handshake: %w", err)
|
||||
}
|
||||
ncs, err := newCipherSuite(v3.Curve(), false, cipher, fips140.Enforced())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cs.v3Cert = v3
|
||||
cs.v3Credential = handshake.NewCredential(v3, v3hs, privateKey, ncs)
|
||||
}
|
||||
|
||||
if v1 != nil {
|
||||
if pkcs11backed {
|
||||
//NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
|
||||
} else {
|
||||
if err := v1.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
|
||||
if err := v1.VerifyPrivateKey(privateKeyCurve, classicalKey); err != nil {
|
||||
return nil, fmt.Errorf("private key is not a pair with public key in nebula cert: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -433,7 +530,7 @@ func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, p
|
||||
return nil, err
|
||||
}
|
||||
cs.v1Cert = v1
|
||||
cs.v1Credential = handshake.NewCredential(v1, v1hs, privateKey, ncs)
|
||||
cs.v1Credential = handshake.NewCredential(v1, v1hs, classicalKey, ncs)
|
||||
|
||||
if cs.initiatingVersion == 0 {
|
||||
cs.initiatingVersion = cert.Version1
|
||||
@@ -444,7 +541,7 @@ func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, p
|
||||
if pkcs11backed {
|
||||
//NOTE: We do not currently have a method to verify a public private key pair when the private key is in an hsm
|
||||
} else {
|
||||
if err := v2.VerifyPrivateKey(privateKeyCurve, privateKey); err != nil {
|
||||
if err := v2.VerifyPrivateKey(privateKeyCurve, classicalKey); err != nil {
|
||||
return nil, fmt.Errorf("private key is not a pair with public key in nebula cert: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -458,7 +555,7 @@ func newCertState(dv cert.Version, v1, v2 cert.Certificate, pkcs11backed bool, p
|
||||
return nil, err
|
||||
}
|
||||
cs.v2Cert = v2
|
||||
cs.v2Credential = handshake.NewCredential(v2, v2hs, privateKey, ncs)
|
||||
cs.v2Credential = handshake.NewCredential(v2, v2hs, classicalKey, ncs)
|
||||
|
||||
if cs.initiatingVersion == 0 {
|
||||
cs.initiatingVersion = cert.Version2
|
||||
|
||||
+46
@@ -1,10 +1,15 @@
|
||||
package nebula
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -92,3 +97,44 @@ func TestNewCipherSuiteUnsupportedCurve(t *testing.T) {
|
||||
assert.True(t, strings.HasPrefix(err.Error(), "unsupported curve:"), "got: %v", err)
|
||||
assert.Nil(t, cs)
|
||||
}
|
||||
|
||||
func TestNewCertStateFromConfig_V3(t *testing.T) {
|
||||
ca, _, caKey, _ := cert_test.NewTestCaCert(cert.Version3, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||
host, _, keyPEM, certPEM := cert_test.NewTestCert(cert.Version3, cert.Curve_CURVE25519, ca, caKey, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")}, nil, nil)
|
||||
v2PEM, err := cert.V2Form(host).MarshalPEM()
|
||||
require.NoError(t, err)
|
||||
key, _, _, err := cert.UnmarshalPrivateKeyFromPEM(keyPEM)
|
||||
require.NoError(t, err)
|
||||
classicalPEM := cert.MarshalPrivateKeyToPEM(cert.Curve_CURVE25519, key[:len(key)-cert.MLKEM1024PrivateKeySize])
|
||||
|
||||
load := func(certPEM, keyPEM []byte) (*CertState, error) {
|
||||
c := config.NewC(test.NewLogger())
|
||||
c.Settings["pki"] = map[string]any{"cert": string(certPEM), "key": string(keyPEM)}
|
||||
return newCertStateFromConfig(c, "aes")
|
||||
}
|
||||
|
||||
cs, err := load(certPEM, keyPEM)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, host, cs.GetCredential(cert.Version3).Cert)
|
||||
assert.Equal(t, cert.V2Form(host), cs.GetCredential(cert.Version2).Cert, "the v2 form comes with it")
|
||||
assert.Equal(t, cert.Version2, cs.DefaultVersion(), "classical handshakes still start with v2")
|
||||
|
||||
// Listing the v2 form as well is fine.
|
||||
_, err = load(append(append([]byte{}, certPEM...), v2PEM...), keyPEM)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Any other v2 certificate is not.
|
||||
_, _, _, otherPEM := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, cert.V2Form(ca), caKey[:len(caKey)-cert.MLDSA87PrivateKeySize], "other", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/16")}, nil, nil)
|
||||
_, err = load(append(append([]byte{}, certPEM...), otherPEM...), keyPEM)
|
||||
require.ErrorContains(t, err, "not the v2 form of the v3 certificate")
|
||||
|
||||
// A v3 certificate needs the composite key.
|
||||
_, err = load(certPEM, classicalPEM)
|
||||
require.ErrorContains(t, err, "not a pair")
|
||||
|
||||
// A composite key also serves a lone v2 certificate.
|
||||
cs, err = load(v2PEM, keyPEM)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, cs.GetCredential(cert.Version3))
|
||||
assert.NotNil(t, cs.GetCredential(cert.Version2))
|
||||
}
|
||||
+3
-3
@@ -119,7 +119,7 @@ func (rm *relayManager) StartRelays(f *Interface, vpnIp netip.Addr, hh *Handshak
|
||||
InitiatorRelayIndex: idx,
|
||||
}
|
||||
|
||||
switch relayHostInfo.GetCert().Certificate.Version() {
|
||||
switch protocolVersion(relayHostInfo.GetCert().Certificate.Version()) {
|
||||
case cert.Version1:
|
||||
if !f.myVpnAddrs[0].Is4() {
|
||||
hl.Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
|
||||
@@ -163,7 +163,7 @@ func (rm *relayManager) StartRelays(f *Interface, vpnIp netip.Addr, hh *Handshak
|
||||
case Established:
|
||||
hl.Log(context.Background(), level, "Send handshake via relay", "relay", relay.String())
|
||||
_ = f.handshakeManager.sendFragmented(now, later, func(p []byte) error {
|
||||
f.SendVia(relayHostInfo, existingRelay, p, make([]byte, 12), make([]byte, mtu), false, 0)
|
||||
f.sendHandshakeVia(relayHostInfo, existingRelay, p)
|
||||
return nil
|
||||
})
|
||||
case Disestablished:
|
||||
@@ -178,7 +178,7 @@ func (rm *relayManager) StartRelays(f *Interface, vpnIp netip.Addr, hh *Handshak
|
||||
InitiatorRelayIndex: existingRelay.LocalIndex,
|
||||
}
|
||||
|
||||
switch relayHostInfo.GetCert().Certificate.Version() {
|
||||
switch protocolVersion(relayHostInfo.GetCert().Certificate.Version()) {
|
||||
case cert.Version1:
|
||||
if !f.myVpnAddrs[0].Is4() {
|
||||
hl.Error("can not establish v1 relay with a v6 network because the relay is not running a current nebula version")
|
||||
|
||||
+5
-2
@@ -85,8 +85,11 @@ type TesterConn struct {
|
||||
|
||||
func NewListener(l *slog.Logger, s Settings) (Conn, error) {
|
||||
c := &TesterConn{
|
||||
RxPackets: make(chan *Packet, 10),
|
||||
TxPackets: make(chan *Packet, 10),
|
||||
// A fragmented handshake message is a burst of a dozen packets. The
|
||||
// router moves packets one at a time, so if both directions held fewer
|
||||
// than a burst each, two bursts crossing would deadlock it.
|
||||
RxPackets: make(chan *Packet, 64),
|
||||
TxPackets: make(chan *Packet, 64),
|
||||
done: make(chan struct{}),
|
||||
l: l,
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user