controller.go 6.5 KB

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