webhook.go 6.2 KB

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