webhook.go 7.5 KB

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