Skip to content

Commit b6d65fe

Browse files
committed
enable webhook server set-up mTLS service to verify client's certificate according to the given CAName
1 parent 37a5c61 commit b6d65fe

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

pkg/webhook/server.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ package webhook
1919
import (
2020
"context"
2121
"crypto/tls"
22+
"crypto/x509"
2223
"fmt"
24+
"io/ioutil"
2325
"net"
2426
"net/http"
2527
"os"
@@ -57,6 +59,10 @@ type Server struct {
5759
// CertName is the server key name. Defaults to tls.key.
5860
KeyName string
5961

62+
// CAName is the CA certificate name which server used to verify remote(client)'s certificate.
63+
// Defaults to "", which means server does not verify client's certificate.
64+
CAName string
65+
6066
// WebhookMux is the multiplexer that handles different webhooks.
6167
WebhookMux *http.ServeMux
6268

@@ -168,6 +174,23 @@ func (s *Server) Start(stop <-chan struct{}) error {
168174
GetCertificate: certWatcher.GetCertificate,
169175
}
170176

177+
// load CA to verify client certificate
178+
if len(s.CAName) > 0 {
179+
certPool := x509.NewCertPool()
180+
clientCABytes, err := ioutil.ReadFile(filepath.Join(s.CertDir, s.CAName))
181+
if err != nil {
182+
return fmt.Errorf("failed to read client CA cert: %v", err)
183+
}
184+
185+
ok := certPool.AppendCertsFromPEM(clientCABytes)
186+
if !ok {
187+
return fmt.Errorf("failed to append client CA cert to CA pool")
188+
}
189+
190+
cfg.RootCAs = certPool
191+
cfg.ClientAuth = tls.RequireAndVerifyClientCert
192+
}
193+
171194
listener, err := tls.Listen("tcp", net.JoinHostPort(s.Host, strconv.Itoa(int(s.Port))), cfg)
172195
if err != nil {
173196
return err

0 commit comments

Comments
 (0)