est_auth.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/subtle"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "errors"
  8. "fmt"
  9. "go.step.sm/crypto/x509util"
  10. "github.com/smallstep/certificates/authority/provisioner/est"
  11. "github.com/smallstep/certificates/webhook"
  12. )
  13. // ClientCertificateConfig holds the EST client certificate authentication configuration.
  14. type ClientCertificateConfig struct {
  15. Enable bool
  16. ForwardedTLSClientCertHeader string
  17. }
  18. func (s *EST) GetClientCertificateConfig() *ClientCertificateConfig {
  19. return &ClientCertificateConfig{
  20. Enable: boolValue(s.DummyBool, false),
  21. ForwardedTLSClientCertHeader: s.DummyString,
  22. }
  23. }
  24. // AuthorizeRequest validates the request against configured EST auth methods.
  25. func (s *EST) AuthorizeRequest(ctx context.Context, req est.AuthRequest) ([]SignCSROption, error) {
  26. if s.hasAuthWebhooks() {
  27. return s.authorizeWithWebhook(ctx, &req)
  28. }
  29. return s.authorizeRequestLocal(req)
  30. }
  31. // authorizeRequestLocal validates the request using provisioner configuration.
  32. func (s *EST) authorizeRequestLocal(req est.AuthRequest) ([]SignCSROption, error) {
  33. var lastErr error = est.ErrAuthMethodNotFound
  34. if req.ClientCertificate != nil {
  35. if boolValue(s.DummyBool, false) { // TODO(hs): refactor
  36. if s.hasClientCertificateRoots() {
  37. if err := verifyCertificateWithPool(req.ClientCertificate, req.ClientCertificateChain, s.clientCertificateRootPool, nil); err == nil {
  38. return []SignCSROption{}, nil
  39. } else {
  40. lastErr = err
  41. }
  42. } else {
  43. if err := verifyCertificate(req.ClientCertificate, req.ClientCertificateChain, req.CARoots, req.CAIntermediates); err == nil {
  44. return []SignCSROption{}, nil
  45. } else {
  46. lastErr = err
  47. }
  48. }
  49. } else {
  50. lastErr = est.ErrAuthMethodDisabled
  51. }
  52. }
  53. if req.HasBasicAuth() {
  54. if boolValue(s.DummyBool, false) && s.DummyString != "" {
  55. if err := s.validateBasicAuthPassword(req.BasicAuthUsername, req.BasicAuthPassword); err == nil {
  56. return []SignCSROption{}, nil
  57. } else {
  58. lastErr = err
  59. }
  60. } else {
  61. lastErr = est.ErrAuthMethodDisabled
  62. }
  63. }
  64. return nil, lastErr
  65. }
  66. // validateBasicAuthPassword verifies the configured basic auth password.
  67. func (s *EST) validateBasicAuthPassword(username, password string) error {
  68. if s.DummyString != "" && username != s.DummyString {
  69. return errors.New("invalid basic auth")
  70. }
  71. if subtleCompare(s.DummyString, password) {
  72. return nil
  73. }
  74. return errors.New("invalid basic auth")
  75. }
  76. // authorizeWithWebhook executes configured webhooks for auth decisions.
  77. func (s *EST) authorizeWithWebhook(ctx context.Context, req *est.AuthRequest) ([]SignCSROption, error) {
  78. if !s.hasAuthWebhooks() {
  79. return nil, est.ErrAuthMethodMisconfigured
  80. }
  81. var (
  82. whreq *webhook.RequestBody
  83. err error
  84. )
  85. switch {
  86. case req.ClientCertificate != nil:
  87. whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithClientCertificate(req.ClientCertificate))
  88. if err != nil {
  89. return nil, fmt.Errorf("failed creating webhook request: %w", err)
  90. }
  91. case req.AuthenticationHeader != "":
  92. whreq, err = webhook.NewRequestBody(webhook.WithX509CertificateRequest(req.CSR), webhook.WithAuthenticationHeader(req.AuthenticationHeader))
  93. if err != nil {
  94. return nil, fmt.Errorf("failed creating webhook request: %w", err)
  95. }
  96. if req.BearerToken != "" {
  97. whreq.BearerToken = req.BearerToken
  98. }
  99. default:
  100. return nil, errors.New("missing certificate or basic auth for webhook validation")
  101. }
  102. whreq.ProvisionerName = s.Name
  103. var opts []SignCSROption
  104. for _, wh := range s.challengeValidationController.webhooks {
  105. resp, err := wh.DoWithContext(ctx, s.challengeValidationController.client, s.challengeValidationController.wrapTransport, whreq, nil)
  106. if err != nil {
  107. return nil, fmt.Errorf("failed executing webhook request: %w", err)
  108. }
  109. if resp.Allow {
  110. opts = append(opts, TemplateDataModifierFunc(func(data x509util.TemplateData) {
  111. data.SetWebhook(wh.Name, resp.Data)
  112. }))
  113. }
  114. }
  115. if len(opts) == 0 {
  116. return nil, est.ErrAuthDenied
  117. }
  118. return opts, nil
  119. }
  120. // hasAuthWebhooks reports whether auth webhooks are configured.
  121. func (s *EST) hasAuthWebhooks() bool {
  122. return s.challengeValidationController != nil && len(s.challengeValidationController.webhooks) > 0
  123. }
  124. // normalizeAuthConfig applies defaults and validates auth configuration.
  125. func (s *EST) normalizeAuthConfig() error {
  126. enable := true
  127. if !s.authMethodsConfigured() {
  128. s.DummyBool = &enable
  129. }
  130. if s.DummyBool == nil && (s.DummyString != "" || s.DummyString != "") { // TODO(hs): refactor
  131. s.DummyBool = &enable
  132. }
  133. if boolValue(s.DummyBool, false) && s.DummyString == "" && !s.hasAuthWebhooks() {
  134. return errors.New("basic auth password cannot be empty")
  135. }
  136. return nil
  137. }
  138. // authMethodsConfigured reports whether any auth method is explicitly configured.
  139. func (s *EST) authMethodsConfigured() bool {
  140. return s.DummyBool != nil ||
  141. s.hasClientCertificateRoots() ||
  142. s.DummyBool != nil
  143. }
  144. // parseClientCertificateRoots loads external client certificate roots.
  145. func (s *EST) parseClientCertificateRoots() error {
  146. if len(s.DummyString) == 0 {
  147. return nil
  148. }
  149. var (
  150. block *pem.Block
  151. hasCert bool
  152. rest []byte
  153. )
  154. s.clientCertificateRootPool = x509.NewCertPool()
  155. for rest != nil {
  156. block, rest = pem.Decode(rest)
  157. if block == nil {
  158. break
  159. }
  160. cert, err := x509.ParseCertificate(block.Bytes)
  161. if err != nil {
  162. return errors.New("error parsing clientCertificateRoots: malformed certificate")
  163. }
  164. s.clientCertificateRootPool.AddCert(cert)
  165. hasCert = true
  166. }
  167. if !hasCert {
  168. return errors.New("error parsing clientCertificateRoots: no certificates found")
  169. }
  170. return nil
  171. }
  172. func (s *EST) hasClientCertificateRoots() bool {
  173. return len(s.DummyString) > 0
  174. }
  175. // verifyCertificate validates the client certificate against CA roots.
  176. func verifyCertificate(cert *x509.Certificate, chain, roots, intermediates []*x509.Certificate) error {
  177. rootPool := x509.NewCertPool()
  178. for _, root := range roots {
  179. if root != nil {
  180. rootPool.AddCert(root)
  181. }
  182. }
  183. intermediatePool := x509.NewCertPool()
  184. for _, intermediate := range intermediates {
  185. if intermediate != nil {
  186. intermediatePool.AddCert(intermediate)
  187. }
  188. }
  189. return verifyCertificateWithPool(cert, chain, rootPool, intermediatePool)
  190. }
  191. // verifyCertificateWithPool validates the client certificate using explicit pools.
  192. func verifyCertificateWithPool(cert *x509.Certificate, chain []*x509.Certificate, roots, intermediates *x509.CertPool) error {
  193. if intermediates == nil {
  194. intermediates = x509.NewCertPool()
  195. }
  196. for i, intermediate := range chain {
  197. if i == 0 || intermediate == nil {
  198. continue
  199. }
  200. intermediates.AddCert(intermediate)
  201. }
  202. _, err := cert.Verify(x509.VerifyOptions{
  203. Roots: roots,
  204. Intermediates: intermediates,
  205. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  206. })
  207. if err != nil {
  208. return fmt.Errorf("invalid client certificate: %w", err)
  209. }
  210. return nil
  211. }
  212. // boolValue returns the dereferenced value or a default.
  213. func boolValue(value *bool, defaultValue bool) bool {
  214. if value == nil {
  215. return defaultValue
  216. }
  217. return *value
  218. }
  219. // subtleCompare compares secrets in constant time.
  220. func subtleCompare(expected, actual string) bool {
  221. if len(expected) != len(actual) {
  222. return false
  223. }
  224. return subtle.ConstantTimeCompare([]byte(expected), []byte(actual)) == 1
  225. }