Răsfoiți Sursa

add support for tls client certificate forwarded by proxy

Jean-Baptiste Pin 8 luni în urmă
părinte
comite
1587afce96

+ 2 - 1
authority/provisioner/est.go

@@ -19,7 +19,8 @@ type EST struct {
 	ID                            string   `json:"-"`
 	Type                          string   `json:"type"`
 	Name                          string   `json:"name"`
-	EnableTLSClientCertificate    *bool    `json:"enableTLSClientCertificate,omitempty"`
+	EnableTLSClientCertificate    *bool    `json:"enableTlsClientCertificate,omitempty"`
+	ForwardedTLSClientCertHeader  string   `json:"forwardedTlsClientCertHeader,omitempty"`
 	EnableHTTPBasicAuth           *bool    `json:"enableHTTPBasicAuth,omitempty"`
 	BasicAuthUsername             string   `json:"basicAuthUsername,omitempty"`
 	BasicAuthPassword             string   `json:"basicAuthPassword,omitempty"`

+ 15 - 1
authority/provisioner/est_auth.go

@@ -19,6 +19,12 @@ var (
 	ErrESTAuthDenied              = errors.New("est authentication denied")
 )
 
+// ClientCertificateConfig holds the EST client certificate authentication configuration.
+type ClientCertificateConfig struct {
+	Enable                       bool
+	ForwardedTLSClientCertHeader string
+}
+
 // ESTAuthRequest contains authentication material extracted from the request.
 type ESTAuthRequest struct {
 	CSR                    *x509.CertificateRequest
@@ -32,6 +38,14 @@ type ESTAuthRequest struct {
 	BearerToken            string
 }
 
+func (s *EST) GetClientCertificateConfig() *ClientCertificateConfig {
+	fmt.Printf("EST provisioner: %#v\n", s)
+	return &ClientCertificateConfig{
+		Enable:                       boolValue(s.EnableTLSClientCertificate, false),
+		ForwardedTLSClientCertHeader: s.ForwardedTLSClientCertHeader,
+	}
+}
+
 // AuthorizeRequest validates the request against configured EST auth methods.
 func (s *EST) AuthorizeRequest(ctx context.Context, req ESTAuthRequest) ([]SignCSROption, error) {
 	if s.hasAuthWebhooks() {
@@ -101,7 +115,7 @@ func (s *EST) authorizeWithWebhook(ctx context.Context, req *ESTAuthRequest) ([]
 	)
 	switch {
 	case req.ClientCertificate != nil:
-		whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithX509Certificate(nil, req.ClientCertificate))
+		whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithClientCertificate(req.ClientCertificate))
 		if err != nil {
 			return nil, fmt.Errorf("failed creating webhook request: %w", err)
 		}

+ 23 - 21
authority/provisioners.go

@@ -1009,19 +1009,20 @@ func ProvisionerToCertificates(p *linkedca.Provisioner) (provisioner.Interface,
 		enableTLSClientCertificate := cfg.EnableTlsClientCertificate
 		enableHTTPBasicAuth := cfg.EnableHttpBasicAuth
 		return &provisioner.EST{
-			ID:                         p.Id,
-			Type:                       p.Type.String(),
-			Name:                       p.Name,
-			EnableTLSClientCertificate: &enableTLSClientCertificate,
-			EnableHTTPBasicAuth:        &enableHTTPBasicAuth,
-			BasicAuthUsername:          cfg.BasicAuthUsername,
-			BasicAuthPassword:          cfg.BasicAuthPassword,
-			ClientCertificateRoots:     provisionerPEMToCertificates(cfg.ClientCertificateRoots),
-			ForceCN:                    cfg.ForceCn,
-			IncludeRoot:                cfg.IncludeRoot,
-			MinimumPublicKeyLength:     int(cfg.MinimumPublicKeyLength),
-			Claims:                     claims,
-			Options:                    options,
+			ID:                           p.Id,
+			Type:                         p.Type.String(),
+			Name:                         p.Name,
+			EnableTLSClientCertificate:   &enableTLSClientCertificate,
+			EnableHTTPBasicAuth:          &enableHTTPBasicAuth,
+			ForwardedTLSClientCertHeader: cfg.ForwardedTlsClientCertHeader,
+			BasicAuthUsername:            cfg.BasicAuthUsername,
+			BasicAuthPassword:            cfg.BasicAuthPassword,
+			ClientCertificateRoots:       provisionerPEMToCertificates(cfg.ClientCertificateRoots),
+			ForceCN:                      cfg.ForceCn,
+			IncludeRoot:                  cfg.IncludeRoot,
+			MinimumPublicKeyLength:       int(cfg.MinimumPublicKeyLength),
+			Claims:                       claims,
+			Options:                      options,
 		}, nil
 	case *linkedca.ProvisionerDetails_Nebula:
 		var roots []byte
@@ -1310,14 +1311,15 @@ func ProvisionerToLinkedca(p provisioner.Interface) (*linkedca.Provisioner, erro
 			Details: &linkedca.ProvisionerDetails{
 				Data: &linkedca.ProvisionerDetails_EST{
 					EST: &linkedca.ESTProvisioner{
-						ForceCn:                    p.ForceCN,
-						EnableTlsClientCertificate: p.EnableTLSClientCertificate != nil && *p.EnableTLSClientCertificate,
-						EnableHttpBasicAuth:         p.EnableHTTPBasicAuth != nil && *p.EnableHTTPBasicAuth,
-						MinimumPublicKeyLength:      cast.Int32(p.MinimumPublicKeyLength),
-						IncludeRoot:                 p.IncludeRoot,
-						BasicAuthUsername:           p.BasicAuthUsername,
-						BasicAuthPassword:           p.BasicAuthPassword,
-						ClientCertificateRoots:      provisionerPEMToLinkedca(p.ClientCertificateRoots),
+						ForceCn:                      p.ForceCN,
+						EnableTlsClientCertificate:   p.EnableTLSClientCertificate != nil && *p.EnableTLSClientCertificate,
+						EnableHttpBasicAuth:          p.EnableHTTPBasicAuth != nil && *p.EnableHTTPBasicAuth,
+						MinimumPublicKeyLength:       cast.Int32(p.MinimumPublicKeyLength),
+						IncludeRoot:                  p.IncludeRoot,
+						BasicAuthUsername:            p.BasicAuthUsername,
+						BasicAuthPassword:            p.BasicAuthPassword,
+						ClientCertificateRoots:       provisionerPEMToLinkedca(p.ClientCertificateRoots),
+						ForwardedTlsClientCertHeader: p.ForwardedTLSClientCertHeader,
 					},
 				},
 			},

+ 28 - 8
est/api/api.go

@@ -100,7 +100,7 @@ func getCACertsHandler(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	writeResponse(w, r, data, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
+	writeResponse(w, data, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
 }
 
 func getCSRAttrs(w http.ResponseWriter, r *http.Request) {
@@ -120,7 +120,7 @@ func getCSRAttrsHandler(w http.ResponseWriter, r *http.Request) {
 		attrs = []byte{}
 	}
 	// Minimal implementation: allow provisioner to return nil/empty for "no attributes".
-	writeResponse(w, r, attrs, "application/csrattrs", http.StatusOK)
+	writeResponse(w, attrs, "application/csrattrs", http.StatusOK)
 }
 
 func enroll(w http.ResponseWriter, r *http.Request) {
@@ -183,7 +183,7 @@ func enrollHandler(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	writeResponse(w, r, signed, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
+	writeResponse(w, signed, "application/pkcs7-mime; smime-type=certs-only", http.StatusOK)
 }
 
 var errMissingAuth = errors.New("missing authentication material")
@@ -193,10 +193,30 @@ func authContextFromRequest(ctx context.Context, r *http.Request) (context.Conte
 	if r.TLS == nil {
 		return ctx, errors.New("missing TLS connection")
 	}
-
-	if len(r.TLS.PeerCertificates) > 0 {
-		ctx = est.NewClientCertificateContext(ctx, r.TLS.PeerCertificates[0])
-		ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
+	prov := est.ProvisionerFromContext(ctx)
+	cfg := prov.GetClientCertificateConfig()
+
+	if cfg.Enable {
+		if cfg.ForwardedTLSClientCertHeader != "" {
+			if forwardedtlsClientCert := r.Header.Get(cfg.ForwardedTLSClientCertHeader); forwardedtlsClientCert != "" {
+				certPEM, err := base64.StdEncoding.DecodeString(forwardedtlsClientCert)
+				if err != nil {
+					// fmt.Printf("failed to decode client cert in forwarded header: %w", err)
+				}
+				certs, err := x509.ParseCertificates(certPEM)
+				if err != nil {
+					// return ctx, fmt.Errorf("failed to parse certificate from header: %w", err)
+				}
+				if len(certs) == 0 {
+					// return ctx, errors.New("no certificates found in header")
+				}
+				ctx = est.NewClientCertificateContext(ctx, certs[0])
+				ctx = est.NewClientCertificateChainContext(ctx, certs)
+			}
+		} else if len(r.TLS.PeerCertificates) > 0 {
+			ctx = est.NewClientCertificateContext(ctx, r.TLS.PeerCertificates[0])
+			ctx = est.NewClientCertificateChainContext(ctx, r.TLS.PeerCertificates)
+		}
 	}
 
 	if authHeader := r.Header.Get("Authorization"); authHeader != "" {
@@ -301,7 +321,7 @@ func requireContentType(r *http.Request, want string) error {
 	return nil
 }
 
-func writeResponse(w http.ResponseWriter, r *http.Request, data []byte, contentType string, status int) {
+func writeResponse(w http.ResponseWriter, data []byte, contentType string, status int) {
 	w.Header().Set("Content-Type", contentType)
 	w.Header().Set("Content-Transfer-Encoding", "base64")
 	w.WriteHeader(status)

+ 1 - 1
est/api/api_test.go

@@ -57,7 +57,7 @@ func Test_writeResponse(t *testing.T) {
 
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
-			writeResponse(tt.args.w, tt.args.r, tt.args.data, tt.args.contentType, tt.args.status)
+			writeResponse(tt.args.w, tt.args.data, tt.args.contentType, tt.args.status)
 			resp := tt.args.w.(*httptest.ResponseRecorder)
 
 			assert.Equal(t, tt.args.status, resp.Code)

+ 1 - 0
est/provisioner.go

@@ -13,6 +13,7 @@ import (
 type Provisioner interface {
 	provisioner.Interface
 	GetOptions() *provisioner.Options
+	GetClientCertificateConfig() *provisioner.ClientCertificateConfig
 	ShouldIncludeRootInChain() bool
 	ShouldIncludeIntermediateInChain() bool
 	GetSigner() (*x509.Certificate, crypto.Signer)

+ 1 - 1
go.mod

@@ -174,4 +174,4 @@ require (
 	google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect
 )
 
-replace github.com/smallstep/linkedca => github.com/jbpin/linkedca v0.0.0-20251224103807-5e7deb3d4d49
+replace github.com/smallstep/linkedca => github.com/jbpin/linkedca v0.0.0-20260119192234-bf5917d1c897

+ 2 - 2
go.sum

@@ -261,8 +261,8 @@ github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
 github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
 github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
 github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
-github.com/jbpin/linkedca v0.0.0-20251224103807-5e7deb3d4d49 h1:rFx5O4hmVJ3fQ90n1PP8fjBWIQoSuBSqbdts6UfnaVk=
-github.com/jbpin/linkedca v0.0.0-20251224103807-5e7deb3d4d49/go.mod h1:bUm0HgkgtOjbnwShtNKu3XPuQ6AA/o680sxTfy9vdYk=
+github.com/jbpin/linkedca v0.0.0-20260119192234-bf5917d1c897 h1:DTvDVMjQ4IGEn+l7g1MqCZpqKFDU5ZTlRzTDTIMFUZs=
+github.com/jbpin/linkedca v0.0.0-20260119192234-bf5917d1c897/go.mod h1:bUm0HgkgtOjbnwShtNKu3XPuQ6AA/o680sxTfy9vdYk=
 github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik=
 github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
 github.com/jmespath/go-jmespath v0.4.1-0.20220621161143-b0104c826a24 h1:liMMTbpW34dhU4az1GN0pTPADwNmvoRSeoZ6PItiqnY=

+ 24 - 0
webhook/options.go

@@ -138,6 +138,30 @@ func WithX5CCertificate(leaf *x509.Certificate) RequestBodyOption {
 	}
 }
 
+func WithClientCertificate(cert *x509.Certificate) RequestBodyOption {
+	return func(rb *RequestBody) error {
+		certificate, err := x509util.NewCertificateFromX509(cert)
+		if err != nil {
+			return err
+		}
+		rb.ClientCertificate = &X509Certificate{
+			Raw:                cert.Raw,
+			PublicKeyAlgorithm: cert.PublicKeyAlgorithm.String(),
+			NotBefore:          cert.NotBefore,
+			NotAfter:           cert.NotAfter,
+			Certificate:        certificate,
+		}
+		if cert.PublicKey != nil {
+			key, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
+			if err != nil {
+				return err
+			}
+			rb.ClientCertificate.PublicKey = key
+		}
+		return nil
+	}
+}
+
 func WithAuthenticationHeader(header string) RequestBodyOption {
 	return func(rb *RequestBody) error {
 		rb.AuthenticationHeader = header

+ 3 - 2
webhook/types.go

@@ -103,6 +103,7 @@ type RequestBody struct {
 	// Set for X5C, AWS, GCP, and Azure provisioners
 	AuthorizationPrincipal string `json:"authorizationPrincipal,omitempty"`
 	// Set for EST webhook requests
-	AuthenticationHeader string `json:"authenticationHeader,omitempty"`
-	BearerToken          string `json:"bearerToken,omitempty"`
+	AuthenticationHeader string           `json:"authenticationHeader,omitempty"`
+	BearerToken          string           `json:"bearerToken,omitempty"`
+	ClientCertificate    *X509Certificate `json:"clientCertificate,omitempty"`
 }