controller.go 7.6 KB

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