k8sSA.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "encoding/pem"
  6. "net/http"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/linkedca"
  9. "go.step.sm/crypto/jose"
  10. "go.step.sm/crypto/pemutil"
  11. "go.step.sm/crypto/sshutil"
  12. "go.step.sm/crypto/x509util"
  13. "github.com/smallstep/certificates/errs"
  14. "github.com/smallstep/certificates/internal/cryptoutil"
  15. )
  16. // NOTE: There can be at most one kubernetes service account provisioner configured
  17. // per instance of step-ca. This is due to a lack of distinguishing information
  18. // contained in kubernetes service account tokens.
  19. const (
  20. // K8sSAName is the default name used for kubernetes service account provisioners.
  21. K8sSAName = "k8sSA-default"
  22. // K8sSAID is the default ID for kubernetes service account provisioners.
  23. K8sSAID = "k8ssa/" + K8sSAName
  24. k8sSAIssuer = "kubernetes/serviceaccount"
  25. )
  26. // jwtPayload extends jwt.Claims with step attributes.
  27. type k8sSAPayload struct {
  28. jose.Claims
  29. Namespace string `json:"kubernetes.io/serviceaccount/namespace,omitempty"`
  30. SecretName string `json:"kubernetes.io/serviceaccount/secret.name,omitempty"`
  31. ServiceAccountName string `json:"kubernetes.io/serviceaccount/service-account.name,omitempty"`
  32. ServiceAccountUID string `json:"kubernetes.io/serviceaccount/service-account.uid,omitempty"`
  33. }
  34. // K8sSA represents a Kubernetes ServiceAccount provisioner; an
  35. // entity trusted to make signature requests.
  36. type K8sSA struct {
  37. *base
  38. ID string `json:"-"`
  39. Type string `json:"type"`
  40. Name string `json:"name"`
  41. PubKeys []byte `json:"publicKeys,omitempty"`
  42. Claims *Claims `json:"claims,omitempty"`
  43. Options *Options `json:"options,omitempty"`
  44. //kauthn kauthn.AuthenticationV1Interface
  45. pubKeys []any
  46. ctl *Controller
  47. }
  48. // GetID returns the provisioner unique identifier. The name and credential id
  49. // should uniquely identify any K8sSA provisioner.
  50. func (p *K8sSA) GetID() string {
  51. if p.ID != "" {
  52. return p.ID
  53. }
  54. return p.GetIDForToken()
  55. }
  56. // GetIDForToken returns an identifier that will be used to load the provisioner
  57. // from a token.
  58. func (p *K8sSA) GetIDForToken() string {
  59. return K8sSAID
  60. }
  61. // GetTokenID returns an unimplemented error and does not use the input ott.
  62. func (p *K8sSA) GetTokenID(string) (string, error) {
  63. return "", ErrNotImplemented
  64. }
  65. // GetName returns the name of the provisioner.
  66. func (p *K8sSA) GetName() string {
  67. return p.Name
  68. }
  69. // GetType returns the type of provisioner.
  70. func (p *K8sSA) GetType() Type {
  71. return TypeK8sSA
  72. }
  73. // GetEncryptedKey returns false, because the kubernetes provisioner does not
  74. // have access to the private key.
  75. func (p *K8sSA) GetEncryptedKey() (string, string, bool) {
  76. return "", "", false
  77. }
  78. // Init initializes and validates the fields of a K8sSA type.
  79. func (p *K8sSA) Init(config Config) (err error) {
  80. switch {
  81. case p.Type == "":
  82. return errors.New("provisioner type cannot be empty")
  83. case p.Name == "":
  84. return errors.New("provisioner name cannot be empty")
  85. }
  86. if p.PubKeys != nil {
  87. var (
  88. block *pem.Block
  89. rest = p.PubKeys
  90. )
  91. for rest != nil {
  92. block, rest = pem.Decode(rest)
  93. if block == nil {
  94. break
  95. }
  96. key, err := pemutil.ParseKey(pem.EncodeToMemory(block))
  97. if err != nil {
  98. return errors.Wrapf(err, "error parsing public key in provisioner '%s'", p.GetName())
  99. }
  100. if !cryptoutil.IsSupportedPublicKey(key) {
  101. return errors.Errorf("Unexpected public key type %T in provisioner %q", key, p.GetName())
  102. }
  103. p.pubKeys = append(p.pubKeys, key)
  104. }
  105. } else {
  106. // TODO: Use the TokenReview API if no pub keys provided. This will need to
  107. // be configured with additional attributes in the K8sSA struct for
  108. // connecting to the kubernetes API server.
  109. return errors.New("K8s Service Account provisioner cannot be initialized without pub keys")
  110. }
  111. /*
  112. // NOTE: Not sure if we should be doing this initialization here ...
  113. // If you have a k8sSA provisioner defined in your config, but you're not
  114. // in a kubernetes pod then your CA will fail to startup. Maybe we just postpone
  115. // creating the authn until token validation time?
  116. if err := checkAccess(k8s.AuthorizationV1()); err != nil {
  117. return errors.Wrapf(err, "error verifying access to kubernetes authz service for provisioner %s", p.GetID())
  118. }
  119. p.kauthn = k8s.AuthenticationV1()
  120. */
  121. p.ctl, err = NewController(p, p.Claims, config, p.Options)
  122. return
  123. }
  124. // authorizeToken performs common jwt authorization actions and returns the
  125. // claims for case specific downstream parsing.
  126. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  127. func (p *K8sSA) authorizeToken(token string, audiences []string) (*k8sSAPayload, error) {
  128. _ = audiences // unused input
  129. jwt, err := jose.ParseSigned(token)
  130. if err != nil {
  131. return nil, errs.Wrap(http.StatusUnauthorized, err,
  132. "k8ssa.authorizeToken; error parsing k8sSA token")
  133. }
  134. var (
  135. valid bool
  136. claims k8sSAPayload
  137. )
  138. if p.pubKeys == nil {
  139. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA TokenReview API integration not implemented")
  140. /* NOTE: We plan to support the TokenReview API in a future release.
  141. Below is some code that should be useful when we prioritize
  142. this integration.
  143. tr := kauthnApi.TokenReview{Spec: kauthnApi.TokenReviewSpec{Token: string(token)}}
  144. rvw, err := p.kauthn.TokenReviews().Create(&tr)
  145. if err != nil {
  146. return nil, errors.Wrap(err, "error using kubernetes TokenReview API")
  147. }
  148. if rvw.Status.Error != "" {
  149. return nil, errors.Errorf("error from kubernetes TokenReviewAPI: %s", rvw.Status.Error)
  150. }
  151. if !rvw.Status.Authenticated {
  152. return nil, errors.New("error from kubernetes TokenReviewAPI: token could not be authenticated")
  153. }
  154. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  155. return nil, errors.Wrap(err, "error parsing claims")
  156. }
  157. */
  158. }
  159. for _, pk := range p.pubKeys {
  160. if err = jwt.Claims(pk, &claims); err == nil {
  161. valid = true
  162. break
  163. }
  164. }
  165. if !valid {
  166. return nil, errs.Unauthorized("k8ssa.authorizeToken; error validating k8sSA token and extracting claims")
  167. }
  168. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  169. // more than a few minutes.
  170. if err = claims.Validate(jose.Expected{
  171. Issuer: k8sSAIssuer,
  172. }); err != nil {
  173. return nil, errs.Wrap(http.StatusUnauthorized, err, "k8ssa.authorizeToken; invalid k8sSA token claims")
  174. }
  175. if claims.Subject == "" {
  176. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA token subject cannot be empty")
  177. }
  178. return &claims, nil
  179. }
  180. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  181. // revoke the certificate with serial number in the `sub` property.
  182. func (p *K8sSA) AuthorizeRevoke(_ context.Context, token string) error {
  183. _, err := p.authorizeToken(token, p.ctl.Audiences.Revoke)
  184. return errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeRevoke")
  185. }
  186. // AuthorizeSign validates the given token.
  187. func (p *K8sSA) AuthorizeSign(_ context.Context, token string) ([]SignOption, error) {
  188. claims, err := p.authorizeToken(token, p.ctl.Audiences.Sign)
  189. if err != nil {
  190. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  191. }
  192. // Add some values to use in custom templates.
  193. data := x509util.NewTemplateData()
  194. data.SetCommonName(claims.ServiceAccountName)
  195. if v, err := unsafeParseSigned(token); err == nil {
  196. data.SetToken(v)
  197. }
  198. // Certificate templates: on K8sSA the default template is the certificate
  199. // request.
  200. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultAdminLeafTemplate)
  201. if err != nil {
  202. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  203. }
  204. return []SignOption{
  205. p,
  206. templateOptions,
  207. // modifiers / withOptions
  208. newProvisionerExtensionOption(TypeK8sSA, p.Name, "").WithControllerOptions(p.ctl),
  209. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  210. // validators
  211. defaultPublicKeyValidator{},
  212. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  213. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  214. p.ctl.newWebhookController(data, linkedca.Webhook_X509),
  215. }, nil
  216. }
  217. // AuthorizeRenew returns an error if the renewal is disabled.
  218. func (p *K8sSA) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  219. return p.ctl.AuthorizeRenew(ctx, cert)
  220. }
  221. // AuthorizeSSHSign validates an request for an SSH certificate.
  222. func (p *K8sSA) AuthorizeSSHSign(_ context.Context, token string) ([]SignOption, error) {
  223. if !p.ctl.Claimer.IsSSHCAEnabled() {
  224. return nil, errs.Unauthorized("k8ssa.AuthorizeSSHSign; sshCA is disabled for k8sSA provisioner '%s'", p.GetName())
  225. }
  226. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  227. if err != nil {
  228. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  229. }
  230. // Certificate templates.
  231. // Set some default variables to be used in the templates.
  232. data := sshutil.CreateTemplateData(sshutil.HostCert, claims.ServiceAccountName, []string{claims.ServiceAccountName})
  233. if v, err := unsafeParseSigned(token); err == nil {
  234. data.SetToken(v)
  235. }
  236. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.CertificateRequestTemplate)
  237. if err != nil {
  238. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  239. }
  240. signOptions := []SignOption{templateOptions}
  241. return append(signOptions,
  242. p,
  243. // Require type, key-id and principals in the SignSSHOptions.
  244. &sshCertOptionsRequireValidator{CertType: true, KeyID: true, Principals: true},
  245. // Set the validity bounds if not set.
  246. &sshDefaultDuration{p.ctl.Claimer},
  247. // Validate public key
  248. &sshDefaultPublicKeyValidator{},
  249. // Validate the validity period.
  250. &sshCertValidityValidator{p.ctl.Claimer},
  251. // Require and validate all the default fields in the SSH certificate.
  252. &sshCertDefaultValidator{},
  253. // Ensure that all principal names are allowed
  254. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), p.ctl.getPolicy().getSSHUser()),
  255. // Call webhooks
  256. p.ctl.newWebhookController(data, linkedca.Webhook_SSH),
  257. ), nil
  258. }
  259. /*
  260. func checkAccess(authz kauthz.AuthorizationV1Interface) error {
  261. r := &kauthzApi.SelfSubjectAccessReview{
  262. Spec: kauthzApi.SelfSubjectAccessReviewSpec{
  263. ResourceAttributes: &kauthzApi.ResourceAttributes{
  264. Group: "authentication.k8s.io",
  265. Version: "v1",
  266. Resource: "tokenreviews",
  267. Verb: "create",
  268. },
  269. },
  270. }
  271. rvw, err := authz.SelfSubjectAccessReviews().Create(r)
  272. if err != nil {
  273. return err
  274. }
  275. if !rvw.Status.Allowed {
  276. return fmt.Errorf("Unable to create kubernetes token reviews: %s", rvw.Status.Reason)
  277. }
  278. return nil
  279. }
  280. */