k8sSA.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/pem"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/cli/crypto/pemutil"
  10. "github.com/smallstep/cli/jose"
  11. "golang.org/x/crypto/ed25519"
  12. )
  13. // NOTE: There can be at most one kubernetes service account provisioner configured
  14. // per instance of step-ca. This is due to a lack of distinguishing information
  15. // contained in kubernetes service account tokens.
  16. const (
  17. // K8sSAName is the default name used for kubernetes service account provisioners.
  18. K8sSAName = "k8sSA-default"
  19. // K8sSAID is the default ID for kubernetes service account provisioners.
  20. K8sSAID = "k8ssa/" + K8sSAName
  21. k8sSAIssuer = "kubernetes/serviceaccount"
  22. )
  23. // This number must <= 1. We'll verify this in Init() below.
  24. var numK8sSAProvisioners = 0
  25. // jwtPayload extends jwt.Claims with step attributes.
  26. type k8sSAPayload struct {
  27. jose.Claims
  28. Namespace string `json:"kubernetes.io/serviceaccount/namespace,omitempty"`
  29. SecretName string `json:"kubernetes.io/serviceaccount/secret.name,omitempty"`
  30. ServiceAccountName string `json:"kubernetes.io/serviceaccount/service-account.name,omitempty"`
  31. ServiceAccountUID string `json:"kubernetes.io/serviceaccount/service-account.uid,omitempty"`
  32. }
  33. // K8sSA represents a Kubernetes ServiceAccount provisioner; an
  34. // entity trusted to make signature requests.
  35. type K8sSA struct {
  36. *base
  37. Type string `json:"type"`
  38. Name string `json:"name"`
  39. Claims *Claims `json:"claims,omitempty"`
  40. PubKeys []byte `json:"publicKeys,omitempty"`
  41. claimer *Claimer
  42. audiences Audiences
  43. //kauthn kauthn.AuthenticationV1Interface
  44. pubKeys []interface{}
  45. }
  46. // GetID returns the provisioner unique identifier. The name and credential id
  47. // should uniquely identify any K8sSA provisioner.
  48. func (p *K8sSA) GetID() string {
  49. return K8sSAID
  50. }
  51. // GetTokenID returns an unimplemented error and does not use the input ott.
  52. func (p *K8sSA) GetTokenID(ott string) (string, error) {
  53. return "", errors.New("not implemented")
  54. }
  55. // GetName returns the name of the provisioner.
  56. func (p *K8sSA) GetName() string {
  57. return p.Name
  58. }
  59. // GetType returns the type of provisioner.
  60. func (p *K8sSA) GetType() Type {
  61. return TypeK8sSA
  62. }
  63. // GetEncryptedKey returns false, because the kubernetes provisioner does not
  64. // have access to the private key.
  65. func (p *K8sSA) GetEncryptedKey() (string, string, bool) {
  66. return "", "", false
  67. }
  68. // Init initializes and validates the fields of a K8sSA type.
  69. func (p *K8sSA) Init(config Config) (err error) {
  70. switch {
  71. case p.Type == "":
  72. return errors.New("provisioner type cannot be empty")
  73. case p.Name == "":
  74. return errors.New("provisioner name cannot be empty")
  75. case numK8sSAProvisioners >= 1:
  76. return errors.New("cannot have more than one kubernetes service account provisioner")
  77. }
  78. if p.PubKeys != nil {
  79. var (
  80. block *pem.Block
  81. rest = p.PubKeys
  82. )
  83. for rest != nil {
  84. block, rest = pem.Decode(rest)
  85. if block == nil {
  86. break
  87. }
  88. key, err := pemutil.ParseKey(pem.EncodeToMemory(block))
  89. if err != nil {
  90. return errors.Wrapf(err, "error parsing public key in provisioner %s", p.GetID())
  91. }
  92. switch q := key.(type) {
  93. case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  94. default:
  95. return errors.Errorf("Unexpected public key type %T in provisioner %s", q, p.GetID())
  96. }
  97. p.pubKeys = append(p.pubKeys, key)
  98. }
  99. } else {
  100. // TODO: Use the TokenReview API if no pub keys provided. This will need to
  101. // be configured with additional attributes in the K8sSA struct for
  102. // connecting to the kubernetes API server.
  103. return errors.New("K8s Service Account provisioner cannot be initialized without pub keys")
  104. }
  105. /*
  106. // NOTE: Not sure if we should be doing this initialization here ...
  107. // If you have a k8sSA provisioner defined in your config, but you're not
  108. // in a kubernetes pod then your CA will fail to startup. Maybe we just postpone
  109. // creating the authn until token validation time?
  110. if err := checkAccess(k8s.AuthorizationV1()); err != nil {
  111. return errors.Wrapf(err, "error verifying access to kubernetes authz service for provisioner %s", p.GetID())
  112. }
  113. p.kauthn = k8s.AuthenticationV1()
  114. */
  115. // Update claims with global ones
  116. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  117. return err
  118. }
  119. p.audiences = config.Audiences
  120. numK8sSAProvisioners++
  121. return err
  122. }
  123. // authorizeToken performs common jwt authorization actions and returns the
  124. // claims for case specific downstream parsing.
  125. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  126. func (p *K8sSA) authorizeToken(token string, audiences []string) (*k8sSAPayload, error) {
  127. jwt, err := jose.ParseSigned(token)
  128. if err != nil {
  129. return nil, errors.Wrapf(err, "error parsing token")
  130. }
  131. var (
  132. valid bool
  133. claims k8sSAPayload
  134. )
  135. if p.pubKeys == nil {
  136. return nil, errors.New("TokenReview API integration not implemented")
  137. /* NOTE: We plan to support the TokenReview API in a future release.
  138. Below is some code that should be useful when we prioritize
  139. this integration.
  140. tr := kauthnApi.TokenReview{Spec: kauthnApi.TokenReviewSpec{Token: string(token)}}
  141. rvw, err := p.kauthn.TokenReviews().Create(&tr)
  142. if err != nil {
  143. return nil, errors.Wrap(err, "error using kubernetes TokenReview API")
  144. }
  145. if rvw.Status.Error != "" {
  146. return nil, errors.Errorf("error from kubernetes TokenReviewAPI: %s", rvw.Status.Error)
  147. }
  148. if !rvw.Status.Authenticated {
  149. return nil, errors.New("error from kubernetes TokenReviewAPI: token could not be authenticated")
  150. }
  151. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  152. return nil, errors.Wrap(err, "error parsing claims")
  153. }
  154. */
  155. }
  156. for _, pk := range p.pubKeys {
  157. if err = jwt.Claims(pk, &claims); err == nil {
  158. valid = true
  159. break
  160. }
  161. }
  162. if !valid {
  163. return nil, errors.New("error validating token and extracting claims")
  164. }
  165. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  166. // more than a few minutes.
  167. if err = claims.Validate(jose.Expected{
  168. Issuer: k8sSAIssuer,
  169. }); err != nil {
  170. return nil, errors.Wrapf(err, "invalid token claims")
  171. }
  172. if claims.Subject == "" {
  173. return nil, errors.New("token subject cannot be empty")
  174. }
  175. return &claims, nil
  176. }
  177. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  178. // revoke the certificate with serial number in the `sub` property.
  179. func (p *K8sSA) AuthorizeRevoke(ctx context.Context, token string) error {
  180. _, err := p.authorizeToken(token, p.audiences.Revoke)
  181. return err
  182. }
  183. // AuthorizeSign validates the given token.
  184. func (p *K8sSA) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  185. _, err := p.authorizeToken(token, p.audiences.Sign)
  186. if err != nil {
  187. return nil, err
  188. }
  189. // Check for SSH sign-ing request.
  190. if MethodFromContext(ctx) == SignSSHMethod {
  191. return nil, errors.New("ssh certificates not enabled for k8s ServiceAccount provisioners")
  192. }
  193. return []SignOption{
  194. // modifiers / withOptions
  195. newProvisionerExtensionOption(TypeK8sSA, p.Name, ""),
  196. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  197. // validators
  198. defaultPublicKeyValidator{},
  199. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  200. }, nil
  201. }
  202. // AuthorizeRenewal returns an error if the renewal is disabled.
  203. func (p *K8sSA) AuthorizeRenewal(cert *x509.Certificate) error {
  204. if p.claimer.IsDisableRenewal() {
  205. return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
  206. }
  207. return nil
  208. }
  209. /*
  210. func checkAccess(authz kauthz.AuthorizationV1Interface) error {
  211. r := &kauthzApi.SelfSubjectAccessReview{
  212. Spec: kauthzApi.SelfSubjectAccessReviewSpec{
  213. ResourceAttributes: &kauthzApi.ResourceAttributes{
  214. Group: "authentication.k8s.io",
  215. Version: "v1",
  216. Resource: "tokenreviews",
  217. Verb: "create",
  218. },
  219. },
  220. }
  221. rvw, err := authz.SelfSubjectAccessReviews().Create(r)
  222. if err != nil {
  223. return err
  224. }
  225. if !rvw.Status.Allowed {
  226. return fmt.Errorf("Unable to create kubernetes token reviews: %s", rvw.Status.Reason)
  227. }
  228. return nil
  229. }
  230. */