webhook.go 8.7 KB

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