controller.go 6.7 KB

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