controller.go 8.0 KB

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