4
0

webhook.go 7.1 KB

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