Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

caddytls: clientauth: leaf verifier: make trusted leaf certs source pluggable #6050

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions caddytest/caddy.examplecert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
-----BEGIN CERTIFICATE-----
armadi1809 marked this conversation as resolved.
Show resolved Hide resolved
MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL
MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC
VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx
NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD
TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu
ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j
V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj
gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA
FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE
CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS
BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE
BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju
Wm7DCfrPNGVwFWUQOmsPue9rZBgO
-----END CERTIFICATE-----
37 changes: 34 additions & 3 deletions modules/caddytls/connpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ func (clientauth *ClientAuthentication) ConfigureTLSConfig(cfg *tls.Config) erro
}
trustedLeafCerts = append(trustedLeafCerts, clientCert)
}
clientauth.verifiers = append(clientauth.verifiers, LeafCertClientAuth{TrustedLeafCerts: trustedLeafCerts})
clientauth.verifiers = append(clientauth.verifiers, LeafCertClientAuth{trustedLeafCerts: trustedLeafCerts})
}

// if a custom verification function already exists, wrap it
Expand Down Expand Up @@ -715,7 +715,8 @@ func setDefaultTLSParams(cfg *tls.Config) {

// LeafCertClientAuth verifies the client's leaf certificate.
type LeafCertClientAuth struct {
TrustedLeafCerts []*x509.Certificate
LeafCertificateLoadersRaw []json.RawMessage `json:"leaf_certs_loaders,omitempty" caddy:"namespace=tls.leaf_cert_loader inline_key=loader"`
trustedLeafCerts []*x509.Certificate
}

// CaddyModule returns the Caddy module information.
Expand All @@ -726,6 +727,30 @@ func (LeafCertClientAuth) CaddyModule() caddy.ModuleInfo {
}
}

func (l *LeafCertClientAuth) Provision(ctx caddy.Context) error {
if l.LeafCertificateLoadersRaw == nil {
return nil
}
val, err := ctx.LoadModule(l, "LeafCertificateLoadersRaw")
if err != nil {
return fmt.Errorf("could not parse leaf certificates loaders: %s", err.Error())
}
trustedLeafCertloaders := []LeafCertificateLoader{}
for _, loader := range val.([]any) {
trustedLeafCertloaders = append(trustedLeafCertloaders, loader.(LeafCertificateLoader))
}
trustedLeafCertificates := []*x509.Certificate{}
for _, loader := range trustedLeafCertloaders {
certs, err := loader.LoadLeafCertificates()
if err != nil {
return fmt.Errorf("could not load leaf certificates: %s", err.Error())
}
trustedLeafCertificates = append(trustedLeafCertificates, certs...)
}
l.trustedLeafCerts = trustedLeafCertificates
return nil
}

func (l LeafCertClientAuth) VerifyClientCertificate(rawCerts [][]byte, _ [][]*x509.Certificate) error {
if len(rawCerts) == 0 {
return fmt.Errorf("no client certificate provided")
Expand All @@ -736,7 +761,7 @@ func (l LeafCertClientAuth) VerifyClientCertificate(rawCerts [][]byte, _ [][]*x5
return fmt.Errorf("can't parse the given certificate: %s", err.Error())
}

for _, trustedLeafCert := range l.TrustedLeafCerts {
for _, trustedLeafCert := range l.trustedLeafCerts {
if remoteLeafCert.Equal(trustedLeafCert) {
return nil
}
Expand Down Expand Up @@ -765,6 +790,12 @@ type ConnectionMatcher interface {
Match(*tls.ClientHelloInfo) bool
}

// LeafCertificateLoader is a type that loads the trusted leaf certificates
// for the tls.leaf_cert_loader modules
type LeafCertificateLoader interface {
LoadLeafCertificates() ([]*x509.Certificate, error)
}

// ClientCertificateVerifier is a type which verifies client certificates.
// It is called during verifyPeerCertificate in the TLS handshake.
type ClientCertificateVerifier interface {
Expand Down
72 changes: 72 additions & 0 deletions modules/caddytls/leafderloader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package caddytls

import (
"crypto/x509"
"fmt"

"github.com/caddyserver/caddy/v2"
)

func init() {
caddy.RegisterModule(LeafDERLoader{})
}

// LeafDERLoader loads leaf certificates by
// decoding their DER blocks directly. This has the advantage
// of not needing to store them on disk at all.
type LeafDERLoader struct {
Certificates []string `json:"certs,omitempty"`
}

// Provision implements caddy.Provisioner.
func (pl *LeafDERLoader) Provision(ctx caddy.Context) error {
repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
if !ok {
repl = caddy.NewReplacer()
}
for i, cert := range pl.Certificates {
pl.Certificates[i] = repl.ReplaceKnown(cert, "")
}
return nil
}

// CaddyModule returns the Caddy module information.
func (LeafDERLoader) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "tls.leaf_cert_loader.der",
New: func() caddy.Module { return new(LeafDERLoader) },
}
}

// LoadLeafCertificates returns the certificates contained in pl.
func (pl LeafDERLoader) LoadLeafCertificates() ([]*x509.Certificate, error) {
certs := make([]*x509.Certificate, 0, len(pl.Certificates))
for i, cert := range pl.Certificates {
cert, err := x509.ParseCertificate([]byte(cert))
if err != nil {
return nil, fmt.Errorf("DER cert %d: %v", i, err)
}
certs = append(certs, cert)
}
return certs, nil
}

// Interface guard
var (
_ LeafCertificateLoader = (*LeafDERLoader)(nil)
_ caddy.Provisioner = (*LeafDERLoader)(nil)
)
99 changes: 99 additions & 0 deletions modules/caddytls/leaffileloader.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright 2015 Matthew Holt and The Caddy Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package caddytls

import (
"crypto/x509"
"encoding/pem"
"fmt"
"os"

"github.com/caddyserver/caddy/v2"
)

func init() {
caddy.RegisterModule(LeafFileLoader{})
}

// LeafFileLoader loads leaf certificates from disk.
type LeafFileLoader struct {
Files []string `json:"files,omitempty"`
}

// Provision implements caddy.Provisioner.
func (fl *LeafFileLoader) Provision(ctx caddy.Context) error {
repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
if !ok {
repl = caddy.NewReplacer()
}
for k, path := range fl.Files {
fl.Files[k] = repl.ReplaceKnown(path, "")
}
return nil
}

// CaddyModule returns the Caddy module information.
func (LeafFileLoader) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "tls.leaf_cert_loader.file",
New: func() caddy.Module { return new(LeafFileLoader) },
}
}

// LoadLEafCertificates returns the certificates to be loaded by fl.
mholt marked this conversation as resolved.
Show resolved Hide resolved
func (fl LeafFileLoader) LoadLeafCertificates() ([]*x509.Certificate, error) {
certificates := make([]*x509.Certificate, 0, len(fl.Files))
for _, path := range fl.Files {
ders, err := convertPEMFilesToDERBytes(path)
if err != nil {
return nil, err
}
certs, err := x509.ParseCertificates(ders)
if err != nil {
return nil, err
}
certificates = append(certificates, certs...)
}
return certificates, nil
}

func convertPEMFilesToDERBytes(filename string) ([]byte, error) {
certDataPEM, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
var ders []byte
// while block is not nil, we have more certificates in the file
for block, rest := pem.Decode(certDataPEM); block != nil; block, rest = pem.Decode(rest) {
if block.Type != "CERTIFICATE" {
return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename)
}
ders = append(
ders,
block.Bytes...,
)
}
// if we decoded nothing, return an error
if len(ders) == 0 {
return nil, fmt.Errorf("no CERTIFICATE pem block found in %s", filename)
}
return ders, nil
}

// Interface guard
var (
_ LeafCertificateLoader = (*LeafFileLoader)(nil)
_ caddy.Provisioner = (*LeafFileLoader)(nil)
)
44 changes: 44 additions & 0 deletions modules/caddytls/leaffileloader_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package caddytls

import (
"bytes"
"context"
"encoding/pem"
"os"
"testing"

"github.com/caddyserver/caddy/v2"
)

func TestLeafFileLoader(t *testing.T) {
fl := LeafFileLoader{Files: []string{"../../caddytest/caddy.examplecert.pem"}}
fl.Provision(caddy.Context{Context: context.Background()})

out, err := fl.LoadLeafCertificates()

if err != nil {
t.Errorf("Leaf certs file loading test failed: %v", err)
}
pemBytes := bytes.NewBuffer(nil)
pem.Encode(pemBytes, &pem.Block{Type: "CERTIFICATE", Bytes: out[0].Raw})
armadi1809 marked this conversation as resolved.
Show resolved Hide resolved
os.WriteFile("./test.txt", pemBytes.Bytes(), 0644)
armadi1809 marked this conversation as resolved.
Show resolved Hide resolved

if pemBytes.String() != `-----BEGIN CERTIFICATE-----
MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL
MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC
VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx
NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD
TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu
ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j
V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj
gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA
FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE
CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS
BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE
BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju
Wm7DCfrPNGVwFWUQOmsPue9rZBgO
-----END CERTIFICATE-----
` {
armadi1809 marked this conversation as resolved.
Show resolved Hide resolved
t.Errorf("Leaf Certificate File Loader: Failed to load the correct certificate")
}
}
Loading
Loading