4
0

controller.go 8.3 KB

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