webhook.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. // redactWebhookURLError rewrites a transport error from a webhook call so logs
  166. // keep the webhook name, scheme, host, and underlying cause, while userinfo,
  167. // path, query, and fragment are replaced with "<redacted>" markers. If the URL
  168. // cannot be parsed, it fails closed and the URL renders as "<redacted>".
  169. func redactWebhookURLError(err error, name string) error {
  170. var urlErr *url.Error
  171. if errors.As(err, &urlErr) {
  172. redacted := *urlErr
  173. redacted.URL = redactURLString(urlErr.URL)
  174. return fmt.Errorf("webhook %q: %w", name, &redacted)
  175. }
  176. return err
  177. }
  178. // redactURLString renders a raw URL string with every sensitive part replaced
  179. // by a "<redacted>" marker, failing closed to "<redacted>" when unparseable.
  180. func redactURLString(raw string) string {
  181. u, err := url.Parse(raw)
  182. if err != nil {
  183. return "<redacted>"
  184. }
  185. return redactURL(u)
  186. }
  187. // redactURL renders a URL as scheme://[userinfo@]host with every sensitive
  188. // part replaced by a "<redacted>" marker when present. A root path "/" carries
  189. // nothing sensitive and is kept as-is.
  190. func redactURL(u *url.URL) string {
  191. s := u.Scheme + "://"
  192. if u.User != nil {
  193. s += "<redacted>@"
  194. }
  195. s += u.Host
  196. if u.Path != "" && u.Path != "/" {
  197. s += "/<redacted>"
  198. }
  199. if u.RawQuery != "" {
  200. s += "?<redacted>"
  201. }
  202. if u.Fragment != "" {
  203. s += "#<redacted>"
  204. }
  205. return s
  206. }
  207. func (w *Webhook) DoWithContext(ctx context.Context, client HTTPClient, tw TransportWrapper, reqBody *webhook.RequestBody, data any) (*webhook.ResponseBody, error) {
  208. tmpl, err := template.New("url").Funcs(templates.StepFuncMap()).Parse(w.URL)
  209. if err != nil {
  210. return nil, err
  211. }
  212. buf := &bytes.Buffer{}
  213. if err := tmpl.Execute(buf, data); err != nil {
  214. return nil, err
  215. }
  216. webhookURL := buf.String()
  217. /*
  218. Sending the token to the webhook server is a security risk. A K8sSA
  219. token can be reused multiple times. The webhook can misuse it to get
  220. fake certificates. A webhook can misuse any other token to get its own
  221. certificate before responding.
  222. switch tmpl := data.(type) {
  223. case x509util.TemplateData:
  224. reqBody.Token = tmpl[x509util.TokenKey]
  225. case sshutil.TemplateData:
  226. reqBody.Token = tmpl[sshutil.TokenKey]
  227. }
  228. */
  229. reqBody.Timestamp = time.Now()
  230. reqBytes, err := json.Marshal(reqBody)
  231. if err != nil {
  232. return nil, err
  233. }
  234. retries := 1
  235. retry:
  236. req, err := http.NewRequestWithContext(ctx, "POST", webhookURL, bytes.NewReader(reqBytes))
  237. if err != nil {
  238. return nil, redactWebhookURLError(err, w.Name)
  239. }
  240. req.Header.Set("Content-Type", "application/json")
  241. if requestID, ok := requestid.FromContext(ctx); ok {
  242. req.Header.Set("X-Request-Id", requestID)
  243. }
  244. secret, err := base64.StdEncoding.DecodeString(w.Secret)
  245. if err != nil {
  246. return nil, err
  247. }
  248. h := hmac.New(sha256.New, secret)
  249. h.Write(reqBytes)
  250. sig := h.Sum(nil)
  251. req.Header.Set("X-Smallstep-Signature", hex.EncodeToString(sig))
  252. req.Header.Set("X-Smallstep-Webhook-ID", w.ID)
  253. if w.BearerToken != "" {
  254. req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", w.BearerToken))
  255. } else if w.BasicAuth.Username != "" || w.BasicAuth.Password != "" {
  256. req.SetBasicAuth(w.BasicAuth.Username, w.BasicAuth.Password)
  257. }
  258. if w.DisableTLSClientAuth {
  259. var transport *http.Transport
  260. if ct, ok := client.(poolhttp.Transporter); ok {
  261. transport = ct.Transport()
  262. } else {
  263. transport = httptransport.New()
  264. }
  265. if transport.TLSClientConfig != nil {
  266. transport.TLSClientConfig.GetClientCertificate = nil
  267. transport.TLSClientConfig.Certificates = nil
  268. }
  269. client = &http.Client{
  270. Transport: tw(transport),
  271. }
  272. }
  273. resp, err := client.Do(req)
  274. if err != nil {
  275. if errors.Is(err, context.DeadlineExceeded) {
  276. return nil, redactWebhookURLError(err, w.Name)
  277. } else if retries > 0 {
  278. retries--
  279. time.Sleep(time.Second)
  280. goto retry
  281. }
  282. return nil, redactWebhookURLError(err, w.Name)
  283. }
  284. defer func() {
  285. if err := resp.Body.Close(); err != nil {
  286. log.Printf("Failed to close body of response from webhook %q URL %s", w.Name, redactURLString(w.URL))
  287. }
  288. }()
  289. if resp.StatusCode >= 500 && retries > 0 {
  290. retries--
  291. time.Sleep(time.Second)
  292. goto retry
  293. }
  294. if resp.StatusCode >= 400 {
  295. return nil, fmt.Errorf("Webhook server responded with %d", resp.StatusCode)
  296. }
  297. respBody := &webhook.ResponseBody{}
  298. if err := json.NewDecoder(resp.Body).Decode(respBody); err != nil {
  299. return nil, err
  300. }
  301. return respBody, nil
  302. }