| author | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 20:55:50 UTC |
| committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 21:03:46 UTC |
| parent | 76962a747c0d36eea11c2796fc1d5e74169e13e9 |
| kxd/key_config.go | +20 | -17 |
| kxd/key_config_test.go | +131 | -0 |
| kxd/kxd.go | +4 | -7 |
| tests/run_tests | +37 | -0 |
diff --git a/kxd/key_config.go b/kxd/key_config.go index 7dd9d3b..f87e666 100644 --- a/kxd/key_config.go +++ b/kxd/key_config.go @@ -131,27 +131,30 @@ func (kc *KeyConfig) LoadAllowedHosts() error { return nil } -type verifyError struct { - Cert *x509.Certificate - Err error -} +var errNoClientCert = errors.New("no client certificate") + +// VerifyClientCert checks if the client certificate is allowed to access +// this key. If so, it returns the verified chains. +// +// certs is the chain as sent by the client. Only the first certificate (the +// leaf) is checked against the allowed ones, because it is the only one the +// TLS handshake proves the client has the private key for. The rest are used +// only as intermediates to build a chain from the leaf. +func (kc *KeyConfig) VerifyClientCert( + certs []*x509.Certificate) ([][]*x509.Certificate, error) { + if len(certs) == 0 { + return nil, errNoClientCert + } -// IsAnyCertAllowed checks if any of the given certificates is allowed to -// access this key. If so, it returns the chain for each of them. -func (kc *KeyConfig) IsAnyCertAllowed( - certs []*x509.Certificate) ([][]*x509.Certificate, []verifyError) { opts := x509.VerifyOptions{ - Roots: kc.allowedClientCerts, + Roots: kc.allowedClientCerts, + Intermediates: x509.NewCertPool(), } - errs := []verifyError{} - for _, cert := range certs { - chains, err := cert.Verify(opts) - if err == nil && len(chains) > 0 { - return chains, nil - } - errs = append(errs, verifyError{cert, err}) + for _, cert := range certs[1:] { + opts.Intermediates.AddCert(cert) } - return nil, errs + + return certs[0].Verify(opts) } // IsHostAllowed checks if the given host is allowed to access this key. diff --git a/kxd/key_config_test.go b/kxd/key_config_test.go new file mode 100644 index 0000000..63ea0ea --- /dev/null +++ b/kxd/key_config_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "testing" + "time" +) + +// newCert creates a certificate for the given name, signed by parent (or +// self-signed if parent is nil). +func newCert(t *testing.T, name string, isCA bool, + parent *x509.Certificate, parentKey crypto.Signer) ( + *x509.Certificate, crypto.Signer) { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + + serial, err := rand.Int(rand.Reader, big.NewInt(1<<62)) + if err != nil { + t.Fatal(err) + } + + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{Organization: []string{name}}, + NotBefore: time.Now().Add(-1 * time.Hour), + NotAfter: time.Now().Add(1 * time.Hour), + BasicConstraintsValid: true, + IsCA: isCA, + } + if isCA { + tmpl.KeyUsage = x509.KeyUsageCertSign + } else { + // Same as kxgencert. + tmpl.KeyUsage = x509.KeyUsageDigitalSignature + tmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + } + + if parent == nil { + parent, parentKey = tmpl, key + } + + der, err := x509.CreateCertificate( + rand.Reader, tmpl, parent, key.Public(), parentKey) + if err != nil { + t.Fatal(err) + } + + cert, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return cert, key +} + +func TestVerifyClientCert(t *testing.T) { + // Self-signed client certificates, as generated by kxgencert. + client, _ := newCert(t, "client", false, nil, nil) + attacker, _ := newCert(t, "attacker", false, nil, nil) + + // A CA, an intermediate, and leaves signed by each. + ca, caKey := newCert(t, "ca", true, nil, nil) + inter, interKey := newCert(t, "intermediate", true, ca, caKey) + caLeaf, _ := newCert(t, "ca-leaf", false, ca, caKey) + interLeaf, _ := newCert(t, "inter-leaf", false, inter, interKey) + + kc := NewKeyConfig("") + kc.allowedClientCerts.AddCert(client) + kc.allowedClientCerts.AddCert(ca) + + cases := []struct { + name string + certs []*x509.Certificate + ok bool + }{ + {"no certs", nil, false}, + {"allowed self-signed", []*x509.Certificate{client}, true}, + {"unknown self-signed", []*x509.Certificate{attacker}, false}, + + // Regression test: the allowed certificate is sent, but not as the + // leaf, so the client has not proven it has its private key. + {"allowed cert after leaf", + []*x509.Certificate{attacker, client}, false}, + {"allowed CA after leaf", + []*x509.Certificate{attacker, ca}, false}, + {"intermediate after leaf", + []*x509.Certificate{attacker, inter}, false}, + + // Extra certificates after a valid leaf are ignored. + {"allowed leaf, extra certs", + []*x509.Certificate{client, attacker}, true}, + + // Chains to an allowed CA. + {"CA-signed leaf", []*x509.Certificate{caLeaf}, true}, + {"leaf with intermediate", + []*x509.Certificate{interLeaf, inter}, true}, + {"leaf without intermediate", + []*x509.Certificate{interLeaf}, false}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + chains, err := kc.VerifyClientCert(c.certs) + if c.ok { + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(chains) == 0 || chains[0][0] != c.certs[0] { + t.Errorf("chain does not start with the leaf: %v", + chains) + } + } else { + if err == nil { + t.Errorf("expected error, got chains: %v", chains) + } + if chains != nil { + t.Errorf("expected no chains, got: %v", chains) + } + } + }) + } +} diff --git a/kxd/kxd.go b/kxd/kxd.go index e234355..a852932 100644 --- a/kxd/kxd.go +++ b/kxd/kxd.go @@ -170,13 +170,10 @@ func HandlerV1(w http.ResponseWriter, httpreq *http.Request) { return } - validChains, errs := keyConf.IsAnyCertAllowed(req.TLS.PeerCertificates) - if validChains == nil { - req.Printf("No allowed certificate found (checked %d certs)", - len(errs)) - for i, e := range errs { - req.Printf(" %d: %s %v", i, certToString(e.Cert), e.Err) - } + validChains, err := keyConf.VerifyClientCert(req.TLS.PeerCertificates) + if err != nil { + req.Printf("Client certificate not allowed: %s %v", + certToString(req.TLS.PeerCertificates[0]), err) http.Error(w, "No allowed certificate found", http.StatusForbidden) return diff --git a/tests/run_tests b/tests/run_tests index b9ed18a..24603ed 100755 --- a/tests/run_tests +++ b/tests/run_tests @@ -629,6 +629,43 @@ class TrickyRequests(TestCase): conn.close() self.assertEqual(response.status, 406) + def test_extra_cert_in_chain(self): + """Allowed cert sent after the leaf, without its private key.""" + self.server.new_key( + "k1", + allowed_clients=[self.client.cert()], + allowed_hosts=["localhost"], + ) + + # Make a chain with the attacker's leaf, followed by the allowed + # client certificate. The attacker only has the private key for + # their leaf, which is all the TLS handshake checks. + attacker = ClientConfig(name="attacker") + chain_path = attacker.path + "/chain.pem" + with open(chain_path, "w") as chain: + chain.write(attacker.cert()) + chain.write(self.client.cert()) + + def get(cert_file, key_file): + conn = self.https_connection( + "localhost", 19840, key_file=key_file, cert_file=cert_file + ) + conn.request("GET", "/v1/k1") + response = conn.getresponse() + body = response.read() + conn.close() + return response.status, body + + # Sanity check: the legitimate client gets the key. + status, body = get(self.client.cert_path(), self.client.key_path()) + self.assertEqual(status, 200) + self.assertEqual(body, self.server.keys["k1"]) + + # The attacker must not. + status, body = get(chain_path, attacker.key_path()) + self.assertEqual(status, 403) + self.assertNotEqual(body, self.server.keys["k1"]) + def test_server_cert(self): rawsock = socket.create_connection(("localhost", 19840)) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)