4
0

controller.go 8.5 KB

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