4
0

controller.go 8.2 KB

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