controller.go 7.8 KB

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