webhook.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package controller
  14. import (
  15. "context"
  16. "crypto/tls"
  17. "fmt"
  18. "net/http"
  19. "os"
  20. "os/signal"
  21. "strings"
  22. "syscall"
  23. "time"
  24. "github.com/spf13/cobra"
  25. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  26. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  27. ctrl "sigs.k8s.io/controller-runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/healthz"
  29. "sigs.k8s.io/controller-runtime/pkg/metrics/filters"
  30. "sigs.k8s.io/controller-runtime/pkg/metrics/server"
  31. "sigs.k8s.io/controller-runtime/pkg/webhook"
  32. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  33. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  34. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  35. "github.com/external-secrets/external-secrets/pkg/controllers/crds"
  36. )
  37. const (
  38. errCreateWebhook = "unable to create webhook"
  39. )
  40. func init() {
  41. // kubernetes schemes
  42. utilruntime.Must(clientgoscheme.AddToScheme(scheme))
  43. // external-secrets schemes
  44. utilruntime.Must(esv1.AddToScheme(scheme))
  45. utilruntime.Must(esv1beta1.AddToScheme(scheme))
  46. utilruntime.Must(esv1alpha1.AddToScheme(scheme))
  47. }
  48. var webhookCmd = &cobra.Command{
  49. Use: "webhook",
  50. Short: "Webhook implementation for ExternalSecrets and SecretStores.",
  51. Long: `Webhook implementation for ExternalSecrets and SecretStores.
  52. For more information visit https://external-secrets.io`,
  53. Run: func(_ *cobra.Command, _ []string) {
  54. setupLogger()
  55. c := crds.CertInfo{
  56. CertDir: certDir,
  57. CertName: "tls.crt",
  58. KeyName: "tls.key",
  59. CAName: "ca.crt",
  60. }
  61. err := waitForCerts(c, time.Minute*2)
  62. if err != nil {
  63. setupLog.Error(err, "unable to validate certificates")
  64. os.Exit(1)
  65. }
  66. ctx, cancel := context.WithCancel(context.Background())
  67. go func(c crds.CertInfo, dnsName string, every time.Duration) {
  68. sigs := make(chan os.Signal, 1)
  69. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  70. ticker := time.NewTicker(every)
  71. for {
  72. select {
  73. case <-sigs:
  74. cancel()
  75. case <-ticker.C:
  76. setupLog.Info("validating certs")
  77. err = crds.CheckCerts(c, dnsName, time.Now().Add(certLookaheadInterval))
  78. if err != nil {
  79. setupLog.Error(err, "certs are not valid at now + lookahead, triggering shutdown", "certLookahead", certLookaheadInterval.String())
  80. cancel()
  81. return
  82. }
  83. setupLog.Info("certs are valid")
  84. }
  85. }
  86. }(c, dnsName, certCheckInterval)
  87. cipherList, err := getTLSCipherSuitesIDs(tlsCiphers)
  88. if err != nil {
  89. ctrl.Log.Error(err, "unable to fetch tls ciphers")
  90. os.Exit(1)
  91. }
  92. // Configure TLS options for webhook server
  93. var webhookTLSOpts []func(*tls.Config)
  94. // Add cipher configuration if needed
  95. if len(cipherList) > 0 {
  96. webhookTLSOpts = append(webhookTLSOpts, func(cfg *tls.Config) {
  97. cfg.CipherSuites = cipherList
  98. })
  99. }
  100. // Add TLS version configuration
  101. webhookTLSOpts = append(webhookTLSOpts, func(c *tls.Config) {
  102. c.MinVersion = tlsVersion(tlsMinVersion)
  103. })
  104. // Add HTTP/2 disabling if needed
  105. if !enableHTTP2 {
  106. webhookTLSOpts = append(webhookTLSOpts, disableHTTP2)
  107. }
  108. // Configure metrics server options
  109. metricsServerOpts := server.Options{
  110. BindAddress: metricsAddr,
  111. }
  112. if metricsSecure {
  113. metricsServerOpts.SecureServing = true
  114. metricsServerOpts.CertDir = metricsCertDir
  115. metricsServerOpts.CertName = metricsCertName
  116. metricsServerOpts.KeyName = metricsKeyName
  117. }
  118. if metricsAuth {
  119. metricsServerOpts.FilterProvider = filters.WithAuthenticationAndAuthorization
  120. }
  121. if metricsAuth && !metricsSecure {
  122. setupLog.Error(nil, "--metrics-auth requires --metrics-secure; bearer tokens over plaintext HTTP is not allowed")
  123. os.Exit(1)
  124. }
  125. // Configure TLS options for metrics server
  126. var metricsTLSOpts []func(*tls.Config)
  127. if !enableHTTP2 {
  128. metricsTLSOpts = append(metricsTLSOpts, disableHTTP2)
  129. }
  130. metricsServerOpts.TLSOpts = metricsTLSOpts
  131. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  132. Scheme: scheme,
  133. Metrics: metricsServerOpts,
  134. HealthProbeBindAddress: healthzAddr,
  135. WebhookServer: webhook.NewServer(webhook.Options{
  136. CertDir: certDir,
  137. Port: port,
  138. TLSOpts: webhookTLSOpts,
  139. }),
  140. })
  141. if err != nil {
  142. setupLog.Error(err, "unable to start manager")
  143. os.Exit(1)
  144. }
  145. if err = (&esv1.ExternalSecret{}).SetupWebhookWithManager(mgr); err != nil {
  146. setupLog.Error(err, errCreateWebhook, "webhook", "ExternalSecret-v1")
  147. os.Exit(1)
  148. }
  149. if err = (&esv1.SecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  150. setupLog.Error(err, errCreateWebhook, "webhook", "SecretStore-v1")
  151. os.Exit(1)
  152. }
  153. if err = (&esv1.ClusterSecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  154. setupLog.Error(err, errCreateWebhook, "webhook", "ClusterSecretStore-v1")
  155. os.Exit(1)
  156. }
  157. if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
  158. setupLog.Error(err, "unable to add webhook healthz check")
  159. os.Exit(1)
  160. }
  161. err = mgr.AddReadyzCheck("certs", func(_ *http.Request) error {
  162. return crds.CheckCerts(c, dnsName, time.Now().Add(time.Hour))
  163. })
  164. if err != nil {
  165. setupLog.Error(err, "unable to add certs readyz check")
  166. os.Exit(1)
  167. }
  168. setupLog.Info("starting manager")
  169. if err := mgr.Start(ctx); err != nil {
  170. setupLog.Error(err, "problem running manager")
  171. os.Exit(1)
  172. }
  173. },
  174. }
  175. // tlsVersion converts from human-readable TLS version (for example "1.1")
  176. // to the values accepted by tls.Config (for example 0x301).
  177. func tlsVersion(version string) uint16 {
  178. switch version {
  179. case "":
  180. return tls.VersionTLS10
  181. case "1.0":
  182. return tls.VersionTLS10
  183. case "1.1":
  184. return tls.VersionTLS11
  185. case "1.2":
  186. return tls.VersionTLS12
  187. case "1.3":
  188. return tls.VersionTLS13
  189. default:
  190. return tls.VersionTLS13
  191. }
  192. }
  193. // waitForCerts waits until the certificates become ready.
  194. // If they don't become ready within a given time duration
  195. // this function returns an error.
  196. // certs are generated by the certcontroller.
  197. func waitForCerts(c crds.CertInfo, timeout time.Duration) error {
  198. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  199. defer cancel()
  200. for {
  201. setupLog.Info("validating certs")
  202. err := crds.CheckCerts(c, dnsName, time.Now().Add(time.Hour))
  203. if err == nil {
  204. return nil
  205. }
  206. setupLog.Error(err, "invalid certs. retrying...")
  207. <-time.After(time.Second * 10)
  208. if ctx.Err() != nil {
  209. return ctx.Err()
  210. }
  211. }
  212. }
  213. func getTLSCipherSuitesIDs(cipherListString string) ([]uint16, error) {
  214. if cipherListString == "" {
  215. return nil, nil
  216. }
  217. cipherList := strings.Split(cipherListString, ",")
  218. cipherIDs := map[string]uint16{}
  219. for _, cs := range tls.CipherSuites() {
  220. cipherIDs[cs.Name] = cs.ID
  221. }
  222. ret := make([]uint16, 0, len(cipherList))
  223. for _, c := range cipherList {
  224. id, ok := cipherIDs[c]
  225. if !ok {
  226. return ret, fmt.Errorf("cipher %s was not found", c)
  227. }
  228. ret = append(ret, id)
  229. }
  230. return ret, nil
  231. }
  232. func init() {
  233. rootCmd.AddCommand(webhookCmd)
  234. webhookCmd.Flags().StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
  235. webhookCmd.Flags().StringVar(&healthzAddr, "healthz-addr", ":8081", "The address the health endpoint binds to.")
  236. webhookCmd.Flags().BoolVar(&metricsAuth, "metrics-auth", false, "Enable Kubernetes RBAC-based authentication and authorization for the metrics endpoint.")
  237. webhookCmd.Flags().BoolVar(&metricsSecure, "metrics-secure", false, "Enable HTTPS for the metrics endpoint.")
  238. webhookCmd.Flags().StringVar(&metricsCertDir, "metrics-cert-dir", "", "Directory containing TLS certificate and key for metrics endpoint.")
  239. webhookCmd.Flags().StringVar(&metricsCertName, "metrics-cert-name", "tls.crt", "TLS certificate filename for metrics endpoint.")
  240. webhookCmd.Flags().StringVar(&metricsKeyName, "metrics-key-name", "tls.key", "TLS key filename for metrics endpoint.")
  241. webhookCmd.Flags().IntVar(&port, "port", 10250, "Port number that the webhook server will serve.")
  242. webhookCmd.Flags().StringVar(&dnsName, "dns-name", "localhost", "DNS name to validate certificates with")
  243. webhookCmd.Flags().StringVar(&certDir, "cert-dir", "/tmp/k8s-webhook-server/serving-certs", "path to check for certs")
  244. webhookCmd.Flags().StringVar(&zapTimeEncoding, "zap-time-encoding", "epoch", "Zap time encoding (one of 'epoch', 'millis', 'nano', 'iso8601', 'rfc3339' or 'rfc3339nano')")
  245. webhookCmd.Flags().StringVar(&loglevel, "loglevel", "info", "loglevel to use, one of: debug, info, warn, error, dpanic, panic, fatal")
  246. webhookCmd.Flags().DurationVar(&certCheckInterval, "check-interval", 5*time.Minute, "certificate check interval")
  247. webhookCmd.Flags().DurationVar(&certLookaheadInterval, "lookahead-interval", crds.LookaheadInterval, "certificate check interval")
  248. // https://go.dev/blog/tls-cipher-suites explains the ciphers selection process
  249. webhookCmd.Flags().StringVar(&tlsCiphers, "tls-ciphers", "", "comma separated list of tls ciphers allowed."+
  250. " This does not apply to TLS 1.3 as the ciphers are selected automatically."+
  251. " The order of this list does not give preference to the ciphers, the ordering is done automatically."+
  252. " Full lists of available ciphers can be found at https://pkg.go.dev/crypto/tls#pkg-constants."+
  253. " E.g. 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256'")
  254. webhookCmd.Flags().StringVar(&tlsMinVersion, "tls-min-version", "1.2", "minimum version of TLS supported.")
  255. webhookCmd.Flags().BoolVar(&enableHTTP2, "enable-http2", false,
  256. "If set, HTTP/2 will be enabled for the metrics and webhook server")
  257. }