webhook.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /*
  2. Copyright © 2022 NAME HERE <EMAIL ADDRESS>
  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. http://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 cmd
  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. "go.uber.org/zap/zapcore"
  26. clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  27. ctrl "sigs.k8s.io/controller-runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/log/zap"
  29. "sigs.k8s.io/controller-runtime/pkg/webhook"
  30. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  31. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  32. "github.com/external-secrets/external-secrets/pkg/controllers/crds"
  33. )
  34. const (
  35. errCreateWebhook = "unable to create webhook"
  36. )
  37. func init() {
  38. _ = clientgoscheme.AddToScheme(scheme)
  39. _ = esv1beta1.AddToScheme(scheme)
  40. _ = esv1alpha1.AddToScheme(scheme)
  41. }
  42. var webhookCmd = &cobra.Command{
  43. Use: "webhook",
  44. Short: "Webhook implementation for ExternalSecrets and SecretStores.",
  45. Long: `Webhook implementation for ExternalSecrets and SecretStores.
  46. For more information visit https://external-secrets.io`,
  47. Run: func(cmd *cobra.Command, args []string) {
  48. var lvl zapcore.Level
  49. err := lvl.UnmarshalText([]byte(loglevel))
  50. if err != nil {
  51. setupLog.Error(err, "error unmarshalling loglevel")
  52. os.Exit(1)
  53. }
  54. c := crds.CertInfo{
  55. CertDir: certDir,
  56. CertName: "tls.crt",
  57. KeyName: "tls.key",
  58. CAName: "ca.crt",
  59. }
  60. logger := zap.New(zap.Level(lvl))
  61. ctrl.SetLogger(logger)
  62. err = waitForCerts(c, time.Minute*2)
  63. if err != nil {
  64. setupLog.Error(err, "unable to validate certificates")
  65. os.Exit(1)
  66. }
  67. ctx, cancel := context.WithCancel(context.Background())
  68. go func(c crds.CertInfo, dnsName string, every time.Duration) {
  69. sigs := make(chan os.Signal, 1)
  70. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  71. ticker := time.NewTicker(every)
  72. for {
  73. select {
  74. case <-sigs:
  75. cancel()
  76. case <-ticker.C:
  77. setupLog.Info("validating certs")
  78. err = crds.CheckCerts(c, dnsName, time.Now().Add(certLookaheadInterval))
  79. if err != nil {
  80. cancel()
  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. mgrTLSOptions := func(cfg *tls.Config) {
  92. cfg.CipherSuites = cipherList
  93. }
  94. mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
  95. Scheme: scheme,
  96. MetricsBindAddress: metricsAddr,
  97. HealthProbeBindAddress: healthzAddr,
  98. WebhookServer: &webhook.Server{
  99. CertDir: certDir,
  100. Port: port,
  101. TLSMinVersion: tlsMinVersion,
  102. TLSOpts: []func(*tls.Config){
  103. mgrTLSOptions,
  104. },
  105. },
  106. })
  107. if err != nil {
  108. setupLog.Error(err, "unable to start manager")
  109. os.Exit(1)
  110. }
  111. if err = (&esv1beta1.ExternalSecret{}).SetupWebhookWithManager(mgr); err != nil {
  112. setupLog.Error(err, errCreateWebhook, "webhook", "ExternalSecret-v1beta1")
  113. os.Exit(1)
  114. }
  115. if err = (&esv1beta1.SecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  116. setupLog.Error(err, errCreateWebhook, "webhook", "SecretStore-v1beta1")
  117. os.Exit(1)
  118. }
  119. if err = (&esv1beta1.ClusterSecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  120. setupLog.Error(err, errCreateWebhook, "webhook", "ClusterSecretStore-v1beta1")
  121. os.Exit(1)
  122. }
  123. if err = (&esv1alpha1.ExternalSecret{}).SetupWebhookWithManager(mgr); err != nil {
  124. setupLog.Error(err, errCreateWebhook, "webhook", "ExternalSecret-v1alpha1")
  125. os.Exit(1)
  126. }
  127. if err = (&esv1alpha1.SecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  128. setupLog.Error(err, errCreateWebhook, "webhook", "SecretStore-v1alpha1")
  129. os.Exit(1)
  130. }
  131. if err = (&esv1alpha1.ClusterSecretStore{}).SetupWebhookWithManager(mgr); err != nil {
  132. setupLog.Error(err, errCreateWebhook, "webhook", "ClusterSecretStore-v1alpha1")
  133. os.Exit(1)
  134. }
  135. err = mgr.AddReadyzCheck("certs", func(_ *http.Request) error {
  136. return crds.CheckCerts(c, dnsName, time.Now().Add(time.Hour))
  137. })
  138. if err != nil {
  139. setupLog.Error(err, "unable to add certs readyz check")
  140. os.Exit(1)
  141. }
  142. setupLog.Info("starting manager")
  143. if err := mgr.Start(ctx); err != nil {
  144. setupLog.Error(err, "problem running manager")
  145. os.Exit(1)
  146. }
  147. },
  148. }
  149. // waitForCerts waits until the certificates become ready.
  150. // If they don't become ready within a given time duration
  151. // this function returns an error.
  152. // certs are generated by the certcontroller.
  153. func waitForCerts(c crds.CertInfo, timeout time.Duration) error {
  154. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  155. defer cancel()
  156. for {
  157. setupLog.Info("validating certs")
  158. err := crds.CheckCerts(c, dnsName, time.Now().Add(time.Hour))
  159. if err == nil {
  160. return nil
  161. }
  162. if err != nil {
  163. setupLog.Error(err, "invalid certs. retrying...")
  164. <-time.After(time.Second * 10)
  165. }
  166. if ctx.Err() != nil {
  167. return ctx.Err()
  168. }
  169. }
  170. }
  171. func getTLSCipherSuitesIDs(cipherListString string) ([]uint16, error) {
  172. if cipherListString == "" {
  173. return nil, nil
  174. }
  175. cipherList := strings.Split(cipherListString, ",")
  176. cipherIds := map[string]uint16{}
  177. for _, cs := range tls.CipherSuites() {
  178. cipherIds[cs.Name] = cs.ID
  179. }
  180. ret := make([]uint16, 0, len(cipherList))
  181. for _, c := range cipherList {
  182. id, ok := cipherIds[c]
  183. if !ok {
  184. return ret, fmt.Errorf("cipher %s was not found", c)
  185. }
  186. ret = append(ret, id)
  187. }
  188. return ret, nil
  189. }
  190. func init() {
  191. rootCmd.AddCommand(webhookCmd)
  192. webhookCmd.Flags().StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
  193. webhookCmd.Flags().StringVar(&healthzAddr, "healthz-addr", ":8081", "The address the health endpoint binds to.")
  194. webhookCmd.Flags().IntVar(&port, "port", 10250, "The address the health endpoint binds to.")
  195. webhookCmd.Flags().StringVar(&dnsName, "dns-name", "localhost", "DNS name to validate certificates with")
  196. webhookCmd.Flags().StringVar(&certDir, "cert-dir", "/tmp/k8s-webhook-server/serving-certs", "path to check for certs")
  197. webhookCmd.Flags().StringVar(&loglevel, "loglevel", "info", "loglevel to use, one of: debug, info, warn, error, dpanic, panic, fatal")
  198. webhookCmd.Flags().DurationVar(&certCheckInterval, "check-interval", 5*time.Minute, "certificate check interval")
  199. webhookCmd.Flags().DurationVar(&certLookaheadInterval, "lookahead-interval", crds.LookaheadInterval, "certificate check interval")
  200. // https://go.dev/blog/tls-cipher-suites explains the ciphers selection process
  201. webhookCmd.Flags().StringVar(&tlsCiphers, "tls-ciphers", "", "comma separated list of tls ciphers allowed."+
  202. " This does not apply to TLS 1.3 as the ciphers are selected automatically."+
  203. " The order of this list does not give preference to the ciphers, the ordering is done automatically."+
  204. " Full lists of available ciphers can be found at https://pkg.go.dev/crypto/tls#pkg-constants."+
  205. " E.g. 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256'")
  206. webhookCmd.Flags().StringVar(&tlsMinVersion, "tls-min-version", "1.2", "minimum version of TLS supported. Defaults to 1.2")
  207. }