4
0

controller.go 7.0 KB

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