controller.go 7.4 KB

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