|
| 1 | +/* |
| 2 | +Copyright 2025 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package mtlsserver is an agnhost subcommand implementing a server to build |
| 18 | +// the mTLS with the client and echo the client identity. |
| 19 | +package mtlsserver |
| 20 | + |
| 21 | +import ( |
| 22 | + "crypto/tls" |
| 23 | + "crypto/x509" |
| 24 | + "flag" |
| 25 | + "fmt" |
| 26 | + "log" |
| 27 | + "net/http" |
| 28 | + "os" |
| 29 | + "time" |
| 30 | + |
| 31 | + "github.com/spf13/cobra" |
| 32 | + "k8s.io/component-base/logs" |
| 33 | +) |
| 34 | + |
| 35 | +var CmdMtlsServer = &cobra.Command{ |
| 36 | + Use: "mtlsserver", |
| 37 | + Short: "Server is configured to build mTLS with client and echo client's spiffe identity", |
| 38 | + Args: cobra.MaximumNArgs(0), |
| 39 | + RunE: main, |
| 40 | +} |
| 41 | + |
| 42 | +var ( |
| 43 | + listen string |
| 44 | + serverCredsFile string |
| 45 | + spiffeTrustBundleFile string |
| 46 | +) |
| 47 | + |
| 48 | +func init() { |
| 49 | + CmdMtlsServer.Flags().StringVar(&listen, "listen", "", "<address>:<port> to listen on") |
| 50 | + CmdMtlsServer.Flags().StringVar(&serverCredsFile, "server-creds", "", "Credential bundle with the server key and certificate chain") |
| 51 | + CmdMtlsServer.Flags().StringVar(&spiffeTrustBundleFile, "spiffe-trust-bundle", "", "Trust bundle for verifying client certificates") |
| 52 | +} |
| 53 | + |
| 54 | +func main(cmd *cobra.Command, args []string) error { |
| 55 | + logs.InitLogs() |
| 56 | + defer logs.FlushLogs() |
| 57 | + if err := flag.Set("logtostderr", "true"); err != nil { |
| 58 | + return fmt.Errorf("failed to set flags: %w", err) |
| 59 | + } |
| 60 | + |
| 61 | + if listen == "" || serverCredsFile == "" || spiffeTrustBundleFile == "" { |
| 62 | + return fmt.Errorf("missing required flags") |
| 63 | + } |
| 64 | + |
| 65 | + if err := serve(); err != nil { |
| 66 | + return fmt.Errorf("error while serving: %w", err) |
| 67 | + } |
| 68 | + return nil |
| 69 | +} |
| 70 | + |
| 71 | +func serve() error { |
| 72 | + serveMux := http.NewServeMux() |
| 73 | + serveMux.HandleFunc("GET /spiffe-echo", handleGetSPIFFEEcho) |
| 74 | + |
| 75 | + clientTrustBundlePEM, err := os.ReadFile(spiffeTrustBundleFile) |
| 76 | + if err != nil { |
| 77 | + return fmt.Errorf("while reading SPIFFE trust anchors: %w", err) |
| 78 | + } |
| 79 | + |
| 80 | + rootPool := x509.NewCertPool() |
| 81 | + if ok := rootPool.AppendCertsFromPEM(clientTrustBundlePEM); !ok { |
| 82 | + return fmt.Errorf("failed to append client certs from PEM") |
| 83 | + } |
| 84 | + |
| 85 | + // Pre-load server cert to check early if it's readable |
| 86 | + _, err = tls.LoadX509KeyPair(serverCredsFile, serverCredsFile) |
| 87 | + if err != nil { |
| 88 | + return fmt.Errorf("while loading server key pair: %w", err) |
| 89 | + } |
| 90 | + |
| 91 | + server := &http.Server{ |
| 92 | + Addr: listen, |
| 93 | + |
| 94 | + Handler: serveMux, |
| 95 | + |
| 96 | + TLSConfig: &tls.Config{ |
| 97 | + // Tell the client to send client certs if they have any. Don't |
| 98 | + // pass in roots to verify the client certificate, since we expect |
| 99 | + // multiple types signed by different CAs. Instead, each endpoint |
| 100 | + // will do the appropriate client certificate verification. |
| 101 | + ClientAuth: tls.RequestClientCert, |
| 102 | + }, |
| 103 | + |
| 104 | + ReadTimeout: 30 * time.Second, |
| 105 | + WriteTimeout: 30 * time.Second, |
| 106 | + MaxHeaderBytes: 1 << 20, |
| 107 | + } |
| 108 | + |
| 109 | + // TODO: Auto-reload the server creds |
| 110 | + if err := server.ListenAndServeTLS(serverCredsFile, serverCredsFile); err != nil { |
| 111 | + return fmt.Errorf("while listening: %w", err) |
| 112 | + } |
| 113 | + |
| 114 | + return nil |
| 115 | +} |
| 116 | + |
| 117 | +func handleGetSPIFFEEcho(w http.ResponseWriter, r *http.Request) { |
| 118 | + if len(r.TLS.PeerCertificates) == 0 { |
| 119 | + http.Error(w, "SPIFFE client certificate authentication required", http.StatusUnauthorized) |
| 120 | + return |
| 121 | + } |
| 122 | + |
| 123 | + leafCert := r.TLS.PeerCertificates[0] |
| 124 | + |
| 125 | + // TODO: Use the trust domain from the leaf certificate to select which |
| 126 | + // trust bundle to use, to permit federated use cases. |
| 127 | + |
| 128 | + intermediatePool := x509.NewCertPool() |
| 129 | + if len(r.TLS.PeerCertificates) > 1 { |
| 130 | + for _, intermediate := range r.TLS.PeerCertificates[1:] { |
| 131 | + intermediatePool.AddCert(intermediate) |
| 132 | + } |
| 133 | + } |
| 134 | + rootTrustBundlePEM, err := os.ReadFile(spiffeTrustBundleFile) |
| 135 | + if err != nil { |
| 136 | + log.Printf("Error while reading SPIFFE trust anchors: %v", err) |
| 137 | + http.Error(w, "Internal Error", http.StatusInternalServerError) |
| 138 | + return |
| 139 | + } |
| 140 | + rootPool := x509.NewCertPool() |
| 141 | + rootPool.AppendCertsFromPEM(rootTrustBundlePEM) |
| 142 | + |
| 143 | + chains, err := leafCert.Verify(x509.VerifyOptions{ |
| 144 | + Intermediates: intermediatePool, |
| 145 | + Roots: rootPool, |
| 146 | + }) |
| 147 | + if err != nil { |
| 148 | + log.Printf("Error while verifying SPIFFE client certificate: %v", err) |
| 149 | + http.Error(w, "SPIFFE client certificate authentication required", http.StatusUnauthorized) |
| 150 | + return |
| 151 | + } |
| 152 | + if len(chains) == 0 { |
| 153 | + log.Print("Client certificate did not chain to any roots") |
| 154 | + http.Error(w, "SPIFFE client certificate authentication required", http.StatusUnauthorized) |
| 155 | + return |
| 156 | + } |
| 157 | + |
| 158 | + if len(leafCert.URIs) != 1 { |
| 159 | + log.Printf("SPIFFE client certificate did not have 1 URI SAN, count: %d", len(leafCert.URIs)) |
| 160 | + http.Error(w, "Malformed SPIFFE certificate", http.StatusUnauthorized) |
| 161 | + return |
| 162 | + } |
| 163 | + |
| 164 | + if _, err := w.Write([]byte("Client Identity: " + leafCert.URIs[0].String())); err != nil { |
| 165 | + log.Printf("Error while writing response: %v", err) |
| 166 | + } |
| 167 | +} |
0 commit comments