webhook.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package provisioner
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "log"
  12. "net/http"
  13. "text/template"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/certificates/templates"
  17. "github.com/smallstep/certificates/webhook"
  18. "go.step.sm/linkedca"
  19. )
  20. var ErrWebhookDenied = errors.New("webhook server did not allow request")
  21. type WebhookSetter interface {
  22. SetWebhook(string, any)
  23. }
  24. type WebhookController struct {
  25. client *http.Client
  26. webhooks []*Webhook
  27. certType linkedca.Webhook_CertType
  28. TemplateData WebhookSetter
  29. }
  30. // Enrich fetches data from remote servers and adds returned data to the
  31. // templateData
  32. func (wc *WebhookController) Enrich(req *webhook.RequestBody) error {
  33. if wc == nil {
  34. return nil
  35. }
  36. for _, wh := range wc.webhooks {
  37. if wh.Kind != linkedca.Webhook_ENRICHING.String() {
  38. continue
  39. }
  40. if !wc.isCertTypeOK(wh) {
  41. continue
  42. }
  43. resp, err := wh.Do(wc.client, req, wc.TemplateData)
  44. if err != nil {
  45. return err
  46. }
  47. if !resp.Allow {
  48. return ErrWebhookDenied
  49. }
  50. wc.TemplateData.SetWebhook(wh.Name, resp.Data)
  51. }
  52. return nil
  53. }
  54. // Authorize checks that all remote servers allow the request
  55. func (wc *WebhookController) Authorize(req *webhook.RequestBody) error {
  56. if wc == nil {
  57. return nil
  58. }
  59. for _, wh := range wc.webhooks {
  60. if wh.Kind != linkedca.Webhook_AUTHORIZING.String() {
  61. continue
  62. }
  63. if !wc.isCertTypeOK(wh) {
  64. continue
  65. }
  66. resp, err := wh.Do(wc.client, req, wc.TemplateData)
  67. if err != nil {
  68. return err
  69. }
  70. if !resp.Allow {
  71. return ErrWebhookDenied
  72. }
  73. }
  74. return nil
  75. }
  76. func (wc *WebhookController) isCertTypeOK(wh *Webhook) bool {
  77. if wc.certType == linkedca.Webhook_ALL {
  78. return true
  79. }
  80. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  81. return true
  82. }
  83. return wc.certType.String() == wh.CertType
  84. }
  85. type Webhook struct {
  86. ID string `json:"id"`
  87. Name string `json:"name"`
  88. URL string `json:"url"`
  89. Kind string `json:"kind"`
  90. DisableTLSClientAuth bool `json:"disableTLSClientAuth,omitempty"`
  91. CertType string `json:"certType"`
  92. Secret string `json:"-"`
  93. BearerToken string `json:"-"`
  94. BasicAuth struct {
  95. Username string
  96. Password string
  97. } `json:"-"`
  98. }
  99. func (w *Webhook) Do(client *http.Client, reqBody *webhook.RequestBody, data any) (*webhook.ResponseBody, error) {
  100. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  101. defer cancel()
  102. return w.DoWithContext(ctx, client, reqBody, data)
  103. }
  104. func (w *Webhook) DoWithContext(ctx context.Context, client *http.Client, reqBody *webhook.RequestBody, data any) (*webhook.ResponseBody, error) {
  105. tmpl, err := template.New("url").Funcs(templates.StepFuncMap()).Parse(w.URL)
  106. if err != nil {
  107. return nil, err
  108. }
  109. buf := &bytes.Buffer{}
  110. if err := tmpl.Execute(buf, data); err != nil {
  111. return nil, err
  112. }
  113. url := buf.String()
  114. /*
  115. Sending the token to the webhook server is a security risk. A K8sSA
  116. token can be reused multiple times. The webhook can misuse it to get
  117. fake certificates. A webhook can misuse any other token to get its own
  118. certificate before responding.
  119. switch tmpl := data.(type) {
  120. case x509util.TemplateData:
  121. reqBody.Token = tmpl[x509util.TokenKey]
  122. case sshutil.TemplateData:
  123. reqBody.Token = tmpl[sshutil.TokenKey]
  124. }
  125. */
  126. reqBody.Timestamp = time.Now()
  127. reqBytes, err := json.Marshal(reqBody)
  128. if err != nil {
  129. return nil, err
  130. }
  131. retries := 1
  132. retry:
  133. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(reqBytes))
  134. if err != nil {
  135. return nil, err
  136. }
  137. secret, err := base64.StdEncoding.DecodeString(w.Secret)
  138. if err != nil {
  139. return nil, err
  140. }
  141. sig := hmac.New(sha256.New, secret).Sum(reqBytes)
  142. req.Header.Set("X-Smallstep-Signature", hex.EncodeToString(sig))
  143. req.Header.Set("X-Smallstep-Webhook-ID", w.ID)
  144. if w.BearerToken != "" {
  145. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", w.BearerToken))
  146. } else if w.BasicAuth.Username != "" || w.BasicAuth.Password != "" {
  147. req.SetBasicAuth(w.BasicAuth.Username, w.BasicAuth.Password)
  148. }
  149. if w.DisableTLSClientAuth {
  150. transport, ok := client.Transport.(*http.Transport)
  151. if !ok {
  152. return nil, errors.New("client transport is not a *http.Transport")
  153. }
  154. transport = transport.Clone()
  155. tlsConfig := transport.TLSClientConfig.Clone()
  156. tlsConfig.GetClientCertificate = nil
  157. tlsConfig.Certificates = nil
  158. transport.TLSClientConfig = tlsConfig
  159. client = &http.Client{
  160. Transport: transport,
  161. }
  162. }
  163. resp, err := client.Do(req)
  164. if err != nil {
  165. if errors.Is(err, context.DeadlineExceeded) {
  166. return nil, err
  167. } else if retries > 0 {
  168. retries--
  169. time.Sleep(time.Second)
  170. goto retry
  171. }
  172. return nil, err
  173. }
  174. defer func() {
  175. if err := resp.Body.Close(); err != nil {
  176. log.Printf("Failed to close body of response from %s", w.URL)
  177. }
  178. }()
  179. if resp.StatusCode >= 500 && retries > 0 {
  180. retries--
  181. time.Sleep(time.Second)
  182. goto retry
  183. }
  184. if resp.StatusCode >= 400 {
  185. return nil, fmt.Errorf("Webhook server responded with %d", resp.StatusCode)
  186. }
  187. respBody := &webhook.ResponseBody{}
  188. if err := json.NewDecoder(resp.Body).Decode(respBody); err != nil {
  189. return nil, err
  190. }
  191. return respBody, nil
  192. }