controller.go 7.5 KB

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