controller.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/errs"
  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) *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. }
  83. }
  84. // Identity is the type representing an externally supplied identity that is used
  85. // by provisioners to populate certificate fields.
  86. type Identity struct {
  87. Usernames []string `json:"usernames"`
  88. Permissions `json:"permissions"`
  89. }
  90. // GetIdentityFunc is a function that returns an identity.
  91. type GetIdentityFunc func(ctx context.Context, p Interface, email string) (*Identity, error)
  92. // AuthorizeRenewFunc is a function that returns nil if the renewal of a
  93. // certificate is enabled.
  94. type AuthorizeRenewFunc func(ctx context.Context, p *Controller, cert *x509.Certificate) error
  95. // AuthorizeSSHRenewFunc is a function that returns nil if the renewal of the
  96. // given SSH certificate is enabled.
  97. type AuthorizeSSHRenewFunc func(ctx context.Context, p *Controller, cert *ssh.Certificate) error
  98. // DefaultIdentityFunc return a default identity depending on the provisioner
  99. // type. For OIDC email is always present and the usernames might
  100. // contain empty strings.
  101. func DefaultIdentityFunc(ctx context.Context, p Interface, email string) (*Identity, error) {
  102. switch k := p.(type) {
  103. case *OIDC:
  104. // OIDC principals would be:
  105. // ~~1. Preferred usernames.~~ Note: Under discussion, currently disabled
  106. // 2. Sanitized local.
  107. // 3. Raw local (if different).
  108. // 4. Email address.
  109. name := SanitizeSSHUserPrincipal(email)
  110. if !sshUserRegex.MatchString(name) {
  111. return nil, errors.Errorf("invalid principal '%s' from email '%s'", name, email)
  112. }
  113. usernames := []string{name}
  114. if i := strings.LastIndex(email, "@"); i >= 0 {
  115. usernames = append(usernames, email[:i])
  116. }
  117. usernames = append(usernames, email)
  118. return &Identity{
  119. Usernames: SanitizeStringSlices(usernames),
  120. }, nil
  121. default:
  122. return nil, errors.Errorf("provisioner type '%T' not supported by identity function", k)
  123. }
  124. }
  125. // DefaultAuthorizeRenew is the default implementation of AuthorizeRenew. It
  126. // will return an error if the provisioner has the renewal disabled, if the
  127. // certificate is not yet valid or if the certificate is expired and renew after
  128. // expiry is disabled.
  129. func DefaultAuthorizeRenew(ctx context.Context, p *Controller, cert *x509.Certificate) error {
  130. if p.Claimer.IsDisableRenewal() {
  131. return errs.Unauthorized("renew is disabled for provisioner '%s'", p.GetName())
  132. }
  133. now := time.Now().Truncate(time.Second)
  134. if now.Before(cert.NotBefore) {
  135. return errs.Unauthorized("certificate is not yet valid" + " " + now.UTC().Format(time.RFC3339Nano) + " vs " + cert.NotBefore.Format(time.RFC3339Nano))
  136. }
  137. if now.After(cert.NotAfter) && !p.Claimer.AllowRenewalAfterExpiry() {
  138. // return a custom 401 Unauthorized error with a clearer message for the client
  139. // TODO(hs): these errors likely need to be refactored as a whole; HTTP status codes shouldn't be in this layer.
  140. return errs.New(http.StatusUnauthorized, "The request lacked necessary authorization to be completed: certificate expired on %s", cert.NotAfter)
  141. }
  142. return nil
  143. }
  144. // DefaultAuthorizeSSHRenew is the default implementation of AuthorizeSSHRenew. 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 DefaultAuthorizeSSHRenew(ctx context.Context, p *Controller, cert *ssh.Certificate) error {
  149. if p.Claimer.IsDisableRenewal() {
  150. return errs.Unauthorized("renew is disabled for provisioner '%s'", p.GetName())
  151. }
  152. unixNow := time.Now().Unix()
  153. if after := int64(cert.ValidAfter); after < 0 || unixNow < int64(cert.ValidAfter) {
  154. return errs.Unauthorized("certificate is not yet valid")
  155. }
  156. if before := int64(cert.ValidBefore); cert.ValidBefore != uint64(ssh.CertTimeInfinity) && (unixNow >= before || before < 0) && !p.Claimer.AllowRenewalAfterExpiry() {
  157. return errs.Unauthorized("certificate has expired")
  158. }
  159. return nil
  160. }
  161. var sshUserRegex = regexp.MustCompile("^[a-z][-a-z0-9_]*$")
  162. // SanitizeStringSlices removes duplicated an empty strings.
  163. func SanitizeStringSlices(original []string) []string {
  164. output := []string{}
  165. seen := make(map[string]struct{})
  166. for _, entry := range original {
  167. if entry == "" {
  168. continue
  169. }
  170. if _, value := seen[entry]; !value {
  171. seen[entry] = struct{}{}
  172. output = append(output, entry)
  173. }
  174. }
  175. return output
  176. }
  177. // SanitizeSSHUserPrincipal grabs an email or a string with the format
  178. // local@domain and returns a sanitized version of the local, valid to be used
  179. // as a user name. If the email starts with a letter between a and z, the
  180. // resulting string will match the regular expression `^[a-z][-a-z0-9_]*$`.
  181. func SanitizeSSHUserPrincipal(email string) string {
  182. if i := strings.LastIndex(email, "@"); i >= 0 {
  183. email = email[:i]
  184. }
  185. return strings.Map(func(r rune) rune {
  186. switch {
  187. case r >= 'a' && r <= 'z':
  188. return r
  189. case r >= '0' && r <= '9':
  190. return r
  191. case r == '-':
  192. return '-'
  193. case r == '.': // drop dots
  194. return -1
  195. default:
  196. return '_'
  197. }
  198. }, strings.ToLower(email))
  199. }
  200. func (c *Controller) getPolicy() *policyEngine {
  201. if c == nil {
  202. return nil
  203. }
  204. return c.policy
  205. }