controller.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/errs"
  10. "github.com/smallstep/certificates/internal/httptransport"
  11. "github.com/smallstep/certificates/webhook"
  12. "github.com/smallstep/linkedca"
  13. "golang.org/x/crypto/ssh"
  14. )
  15. // Controller wraps a provisioner with other attributes useful in callback
  16. // functions.
  17. type Controller struct {
  18. Interface
  19. Audiences *Audiences
  20. Claimer *Claimer
  21. IdentityFunc GetIdentityFunc
  22. AuthorizeRenewFunc AuthorizeRenewFunc
  23. AuthorizeSSHRenewFunc AuthorizeSSHRenewFunc
  24. policy *policyEngine
  25. webhookClient *http.Client
  26. webhooks []*Webhook
  27. httpClient *http.Client
  28. wrapTransport httptransport.Wrapper
  29. }
  30. // NewController initializes a new provisioner controller.
  31. func NewController(p Interface, claims *Claims, config Config, options *Options) (*Controller, error) {
  32. claimer, err := NewClaimer(claims, config.Claims)
  33. if err != nil {
  34. return nil, err
  35. }
  36. policy, err := newPolicyEngine(options)
  37. if err != nil {
  38. return nil, err
  39. }
  40. wt := config.WrapTransport
  41. if wt == nil {
  42. wt = httptransport.NoopWrapper()
  43. }
  44. return &Controller{
  45. Interface: p,
  46. Audiences: &config.Audiences,
  47. Claimer: claimer,
  48. IdentityFunc: config.GetIdentityFunc,
  49. AuthorizeRenewFunc: config.AuthorizeRenewFunc,
  50. AuthorizeSSHRenewFunc: config.AuthorizeSSHRenewFunc,
  51. policy: policy,
  52. webhookClient: config.WebhookClient,
  53. webhooks: options.GetWebhooks(),
  54. httpClient: config.HTTPClient,
  55. wrapTransport: wt,
  56. }, nil
  57. }
  58. // GetHTTPClient returns the configured HTTP client or the default one if none
  59. // is configured.
  60. func (c *Controller) GetHTTPClient() *http.Client {
  61. if c.httpClient != nil {
  62. return c.httpClient
  63. }
  64. return &http.Client{}
  65. }
  66. // GetIdentity returns the identity for a given email.
  67. func (c *Controller) GetIdentity(ctx context.Context, email string) (*Identity, error) {
  68. if c.IdentityFunc != nil {
  69. return c.IdentityFunc(ctx, c.Interface, email)
  70. }
  71. return DefaultIdentityFunc(ctx, c.Interface, email)
  72. }
  73. // AuthorizeRenew returns nil if the given cert can be renewed, returns an error
  74. // otherwise.
  75. func (c *Controller) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  76. if c.AuthorizeRenewFunc != nil {
  77. return c.AuthorizeRenewFunc(ctx, c, cert)
  78. }
  79. return DefaultAuthorizeRenew(ctx, c, cert)
  80. }
  81. // AuthorizeSSHRenew returns nil if the given cert can be renewed, returns an
  82. // error otherwise.
  83. func (c *Controller) AuthorizeSSHRenew(ctx context.Context, cert *ssh.Certificate) error {
  84. if c.AuthorizeSSHRenewFunc != nil {
  85. return c.AuthorizeSSHRenewFunc(ctx, c, cert)
  86. }
  87. return DefaultAuthorizeSSHRenew(ctx, c, cert)
  88. }
  89. func (c *Controller) newWebhookController(templateData WebhookSetter, certType linkedca.Webhook_CertType, opts ...webhook.RequestBodyOption) *WebhookController {
  90. client := c.webhookClient
  91. if client == nil {
  92. client = &http.Client{
  93. Transport: c.wrapTransport(httptransport.New()),
  94. }
  95. }
  96. return &WebhookController{
  97. TemplateData: templateData,
  98. client: client,
  99. wrapTransport: c.wrapTransport,
  100. webhooks: c.webhooks,
  101. certType: certType,
  102. options: opts,
  103. }
  104. }
  105. // Identity is the type representing an externally supplied identity that is used
  106. // by provisioners to populate certificate fields.
  107. type Identity struct {
  108. Usernames []string `json:"usernames"`
  109. Permissions `json:"permissions"`
  110. }
  111. // GetIdentityFunc is a function that returns an identity.
  112. type GetIdentityFunc func(ctx context.Context, p Interface, email string) (*Identity, error)
  113. // AuthorizeRenewFunc is a function that returns nil if the renewal of a
  114. // certificate is enabled.
  115. type AuthorizeRenewFunc func(ctx context.Context, p *Controller, cert *x509.Certificate) error
  116. // AuthorizeSSHRenewFunc is a function that returns nil if the renewal of the
  117. // given SSH certificate is enabled.
  118. type AuthorizeSSHRenewFunc func(ctx context.Context, p *Controller, cert *ssh.Certificate) error
  119. // DefaultIdentityFunc return a default identity depending on the provisioner
  120. // type. For OIDC email is always present and the usernames might
  121. // contain empty strings.
  122. func DefaultIdentityFunc(_ context.Context, p Interface, email string) (*Identity, error) {
  123. switch k := p.(type) {
  124. case *OIDC:
  125. // OIDC principals would be:
  126. // ~~1. Preferred usernames.~~ Note: Under discussion, currently disabled
  127. // 2. Sanitized local.
  128. // 3. Raw local (if different).
  129. // 4. Email address.
  130. name := SanitizeSSHUserPrincipal(email)
  131. usernames := []string{name}
  132. if i := strings.LastIndex(email, "@"); i >= 0 {
  133. usernames = append(usernames, email[:i])
  134. }
  135. usernames = append(usernames, email)
  136. return &Identity{
  137. // Remove duplicated and empty usernames.
  138. Usernames: SanitizeStringSlices(usernames),
  139. }, nil
  140. default:
  141. return nil, errors.Errorf("provisioner type '%T' not supported by identity function", k)
  142. }
  143. }
  144. // DefaultAuthorizeRenew is the default implementation of AuthorizeRenew. It
  145. // will return an error if the provisioner has the renewal disabled, if the
  146. // certificate is not yet valid or if the certificate is expired and renew after
  147. // expiry is disabled.
  148. func DefaultAuthorizeRenew(_ context.Context, p *Controller, cert *x509.Certificate) error {
  149. if p.Claimer.IsDisableRenewal() {
  150. return errs.Unauthorized("renew is disabled for provisioner '%s'", p.GetName())
  151. }
  152. now := time.Now().Truncate(time.Second)
  153. if now.Before(cert.NotBefore) {
  154. return errs.Unauthorized("certificate is not yet valid" + " " + now.UTC().Format(time.RFC3339Nano) + " vs " + cert.NotBefore.Format(time.RFC3339Nano))
  155. }
  156. if now.After(cert.NotAfter) && !p.Claimer.AllowRenewalAfterExpiry() {
  157. // return a custom 401 Unauthorized error with a clearer message for the client
  158. // TODO(hs): these errors likely need to be refactored as a whole; HTTP status codes shouldn't be in this layer.
  159. return errs.New(http.StatusUnauthorized, "The request lacked necessary authorization to be completed: certificate expired on %s", cert.NotAfter)
  160. }
  161. return nil
  162. }
  163. // DefaultAuthorizeSSHRenew is the default implementation of AuthorizeSSHRenew. It
  164. // will return an error if the provisioner has the renewal disabled, if the
  165. // certificate is not yet valid or if the certificate is expired and renew after
  166. // expiry is disabled.
  167. func DefaultAuthorizeSSHRenew(_ context.Context, p *Controller, cert *ssh.Certificate) error {
  168. if p.Claimer.IsDisableRenewal() {
  169. return errs.Unauthorized("renew is disabled for provisioner '%s'", p.GetName())
  170. }
  171. unixNow := time.Now().Unix()
  172. if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
  173. return errs.Unauthorized("certificate is not yet valid")
  174. }
  175. if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(ssh.CertTimeInfinity) && (unixNow >= before || before < 0) && !p.Claimer.AllowRenewalAfterExpiry() {
  176. return errs.Unauthorized("certificate has expired")
  177. }
  178. return nil
  179. }
  180. // SanitizeStringSlices removes duplicated an empty strings.
  181. func SanitizeStringSlices(original []string) []string {
  182. output := []string{}
  183. seen := make(map[string]struct{})
  184. for _, entry := range original {
  185. if entry == "" {
  186. continue
  187. }
  188. if _, value := seen[entry]; !value {
  189. seen[entry] = struct{}{}
  190. output = append(output, entry)
  191. }
  192. }
  193. return output
  194. }
  195. // SanitizeSSHUserPrincipal grabs an email or a string with the format
  196. // local@domain and returns a sanitized version of the local, valid to be used
  197. // as a user name. If the email starts with a letter between a and z, the
  198. // resulting string will match the regular expression `^[a-z][-a-z0-9_]*$`.
  199. func SanitizeSSHUserPrincipal(email string) string {
  200. if i := strings.LastIndex(email, "@"); i >= 0 {
  201. email = email[:i]
  202. }
  203. return strings.Map(func(r rune) rune {
  204. switch {
  205. case r >= 'a' && r <= 'z':
  206. return r
  207. case r >= '0' && r <= '9':
  208. return r
  209. case r == '-':
  210. return '-'
  211. case r == '.': // drop dots
  212. return -1
  213. default:
  214. return '_'
  215. }
  216. }, strings.ToLower(email))
  217. }
  218. func (c *Controller) getPolicy() *policyEngine {
  219. if c == nil {
  220. return nil
  221. }
  222. return c.policy
  223. }