webhook.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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/linkedca"
  17. "github.com/smallstep/certificates/authority/poolhttp"
  18. "github.com/smallstep/certificates/internal/httptransport"
  19. "github.com/smallstep/certificates/middleware/requestid"
  20. "github.com/smallstep/certificates/templates"
  21. "github.com/smallstep/certificates/webhook"
  22. )
  23. var ErrWebhookDenied = errors.New("webhook server did not allow request")
  24. type WebhookSetter interface {
  25. SetWebhook(string, any)
  26. }
  27. type WebhookController struct {
  28. client HTTPClient
  29. wrapTransport httptransport.Wrapper
  30. webhooks []*Webhook
  31. certType linkedca.Webhook_CertType
  32. options []webhook.RequestBodyOption
  33. TemplateData WebhookSetter
  34. }
  35. // Enrich fetches data from remote servers and adds returned data to the
  36. // templateData
  37. func (wc *WebhookController) Enrich(ctx context.Context, req *webhook.RequestBody) error {
  38. if wc == nil {
  39. return nil
  40. }
  41. // Apply extra options in the webhook controller
  42. for _, fn := range wc.options {
  43. if err := fn(req); err != nil {
  44. return err
  45. }
  46. }
  47. for _, wh := range wc.webhooks {
  48. if wh.Kind != linkedca.Webhook_ENRICHING.String() {
  49. continue
  50. }
  51. if !wc.isCertTypeOK(wh) {
  52. continue
  53. }
  54. whCtx, cancel := context.WithTimeout(ctx, time.Second*10)
  55. defer cancel() //nolint:gocritic // every request canceled with its own timeout
  56. resp, err := wh.DoWithContext(whCtx, wc.client, wc.wrapTransport, req, wc.TemplateData)
  57. if err != nil {
  58. return err
  59. }
  60. if !resp.Allow {
  61. if resp.Error != nil {
  62. return resp.Error
  63. }
  64. return ErrWebhookDenied
  65. }
  66. wc.TemplateData.SetWebhook(wh.Name, resp.Data)
  67. }
  68. return nil
  69. }
  70. // Authorize checks that all remote servers allow the request
  71. func (wc *WebhookController) Authorize(ctx context.Context, req *webhook.RequestBody) error {
  72. if wc == nil {
  73. return nil
  74. }
  75. // Apply extra options in the webhook controller
  76. for _, fn := range wc.options {
  77. if err := fn(req); err != nil {
  78. return err
  79. }
  80. }
  81. for _, wh := range wc.webhooks {
  82. if wh.Kind != linkedca.Webhook_AUTHORIZING.String() {
  83. continue
  84. }
  85. if !wc.isCertTypeOK(wh) {
  86. continue
  87. }
  88. whCtx, cancel := context.WithTimeout(ctx, time.Second*10)
  89. defer cancel() //nolint:gocritic // every request canceled with its own timeout
  90. resp, err := wh.DoWithContext(whCtx, wc.client, wc.wrapTransport, req, wc.TemplateData)
  91. if err != nil {
  92. return err
  93. }
  94. if !resp.Allow {
  95. if resp.Error != nil {
  96. return resp.Error
  97. }
  98. return ErrWebhookDenied
  99. }
  100. }
  101. return nil
  102. }
  103. func (wc *WebhookController) isCertTypeOK(wh *Webhook) bool {
  104. if wc.certType == linkedca.Webhook_ALL {
  105. return true
  106. }
  107. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  108. return true
  109. }
  110. return wc.certType.String() == wh.CertType
  111. }
  112. type Webhook struct {
  113. ID string `json:"id"`
  114. Name string `json:"name"`
  115. URL string `json:"url"`
  116. Kind string `json:"kind"`
  117. DisableTLSClientAuth bool `json:"disableTLSClientAuth,omitempty"`
  118. CertType string `json:"certType"`
  119. Secret string `json:"-"`
  120. BearerToken string `json:"-"`
  121. BasicAuth struct {
  122. Username string
  123. Password string
  124. } `json:"-"`
  125. }
  126. // TransportWrapper wraps the set of functions mapping [http.Transport] references to
  127. // [http.RoundTripper].
  128. type TransportWrapper = httptransport.Wrapper
  129. func (w *Webhook) DoWithContext(ctx context.Context, client HTTPClient, tw TransportWrapper, reqBody *webhook.RequestBody, data any) (*webhook.ResponseBody, error) {
  130. tmpl, err := template.New("url").Funcs(templates.StepFuncMap()).Parse(w.URL)
  131. if err != nil {
  132. return nil, err
  133. }
  134. buf := &bytes.Buffer{}
  135. if err := tmpl.Execute(buf, data); err != nil {
  136. return nil, err
  137. }
  138. url := buf.String()
  139. /*
  140. Sending the token to the webhook server is a security risk. A K8sSA
  141. token can be reused multiple times. The webhook can misuse it to get
  142. fake certificates. A webhook can misuse any other token to get its own
  143. certificate before responding.
  144. switch tmpl := data.(type) {
  145. case x509util.TemplateData:
  146. reqBody.Token = tmpl[x509util.TokenKey]
  147. case sshutil.TemplateData:
  148. reqBody.Token = tmpl[sshutil.TokenKey]
  149. }
  150. */
  151. reqBody.Timestamp = time.Now()
  152. reqBytes, err := json.Marshal(reqBody)
  153. if err != nil {
  154. return nil, err
  155. }
  156. retries := 1
  157. retry:
  158. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(reqBytes))
  159. if err != nil {
  160. return nil, err
  161. }
  162. if requestID, ok := requestid.FromContext(ctx); ok {
  163. req.Header.Set("X-Request-Id", requestID)
  164. }
  165. secret, err := base64.StdEncoding.DecodeString(w.Secret)
  166. if err != nil {
  167. return nil, err
  168. }
  169. h := hmac.New(sha256.New, secret)
  170. h.Write(reqBytes)
  171. sig := h.Sum(nil)
  172. req.Header.Set("X-Smallstep-Signature", hex.EncodeToString(sig))
  173. req.Header.Set("X-Smallstep-Webhook-ID", w.ID)
  174. if w.BearerToken != "" {
  175. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", w.BearerToken))
  176. } else if w.BasicAuth.Username != "" || w.BasicAuth.Password != "" {
  177. req.SetBasicAuth(w.BasicAuth.Username, w.BasicAuth.Password)
  178. }
  179. if w.DisableTLSClientAuth {
  180. var transport *http.Transport
  181. if ct, ok := client.(poolhttp.Transporter); ok {
  182. transport = ct.Transport()
  183. } else {
  184. transport = httptransport.New()
  185. }
  186. if transport.TLSClientConfig != nil {
  187. transport.TLSClientConfig.GetClientCertificate = nil
  188. transport.TLSClientConfig.Certificates = nil
  189. }
  190. client = &http.Client{
  191. Transport: tw(transport),
  192. }
  193. }
  194. resp, err := client.Do(req)
  195. if err != nil {
  196. if errors.Is(err, context.DeadlineExceeded) {
  197. return nil, err
  198. } else if retries > 0 {
  199. retries--
  200. time.Sleep(time.Second)
  201. goto retry
  202. }
  203. return nil, err
  204. }
  205. defer func() {
  206. if err := resp.Body.Close(); err != nil {
  207. log.Printf("Failed to close body of response from %s", w.URL)
  208. }
  209. }()
  210. if resp.StatusCode >= 500 && retries > 0 {
  211. retries--
  212. time.Sleep(time.Second)
  213. goto retry
  214. }
  215. if resp.StatusCode >= 400 {
  216. return nil, fmt.Errorf("Webhook server responded with %d", resp.StatusCode)
  217. }
  218. respBody := &webhook.ResponseBody{}
  219. if err := json.NewDecoder(resp.Body).Decode(respBody); err != nil {
  220. return nil, err
  221. }
  222. return respBody, nil
  223. }