k8sSA.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/pem"
  8. "net/http"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/errs"
  11. "github.com/smallstep/cli/crypto/pemutil"
  12. "github.com/smallstep/cli/jose"
  13. "golang.org/x/crypto/ed25519"
  14. )
  15. // NOTE: There can be at most one kubernetes service account provisioner configured
  16. // per instance of step-ca. This is due to a lack of distinguishing information
  17. // contained in kubernetes service account tokens.
  18. const (
  19. // K8sSAName is the default name used for kubernetes service account provisioners.
  20. K8sSAName = "k8sSA-default"
  21. // K8sSAID is the default ID for kubernetes service account provisioners.
  22. K8sSAID = "k8ssa/" + K8sSAName
  23. k8sSAIssuer = "kubernetes/serviceaccount"
  24. )
  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. }
  76. if p.PubKeys != nil {
  77. var (
  78. block *pem.Block
  79. rest = p.PubKeys
  80. )
  81. for rest != nil {
  82. block, rest = pem.Decode(rest)
  83. if block == nil {
  84. break
  85. }
  86. key, err := pemutil.ParseKey(pem.EncodeToMemory(block))
  87. if err != nil {
  88. return errors.Wrapf(err, "error parsing public key in provisioner %s", p.GetID())
  89. }
  90. switch q := key.(type) {
  91. case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
  92. default:
  93. return errors.Errorf("Unexpected public key type %T in provisioner %s", q, p.GetID())
  94. }
  95. p.pubKeys = append(p.pubKeys, key)
  96. }
  97. } else {
  98. // TODO: Use the TokenReview API if no pub keys provided. This will need to
  99. // be configured with additional attributes in the K8sSA struct for
  100. // connecting to the kubernetes API server.
  101. return errors.New("K8s Service Account provisioner cannot be initialized without pub keys")
  102. }
  103. /*
  104. // NOTE: Not sure if we should be doing this initialization here ...
  105. // If you have a k8sSA provisioner defined in your config, but you're not
  106. // in a kubernetes pod then your CA will fail to startup. Maybe we just postpone
  107. // creating the authn until token validation time?
  108. if err := checkAccess(k8s.AuthorizationV1()); err != nil {
  109. return errors.Wrapf(err, "error verifying access to kubernetes authz service for provisioner %s", p.GetID())
  110. }
  111. p.kauthn = k8s.AuthenticationV1()
  112. */
  113. // Update claims with global ones
  114. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  115. return err
  116. }
  117. p.audiences = config.Audiences
  118. return err
  119. }
  120. // authorizeToken performs common jwt authorization actions and returns the
  121. // claims for case specific downstream parsing.
  122. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  123. func (p *K8sSA) authorizeToken(token string, audiences []string) (*k8sSAPayload, error) {
  124. jwt, err := jose.ParseSigned(token)
  125. if err != nil {
  126. return nil, errs.Wrap(http.StatusUnauthorized, err,
  127. "k8ssa.authorizeToken; error parsing k8sSA token")
  128. }
  129. var (
  130. valid bool
  131. claims k8sSAPayload
  132. )
  133. if p.pubKeys == nil {
  134. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA TokenReview API integration not implemented")
  135. /* NOTE: We plan to support the TokenReview API in a future release.
  136. Below is some code that should be useful when we prioritize
  137. this integration.
  138. tr := kauthnApi.TokenReview{Spec: kauthnApi.TokenReviewSpec{Token: string(token)}}
  139. rvw, err := p.kauthn.TokenReviews().Create(&tr)
  140. if err != nil {
  141. return nil, errors.Wrap(err, "error using kubernetes TokenReview API")
  142. }
  143. if rvw.Status.Error != "" {
  144. return nil, errors.Errorf("error from kubernetes TokenReviewAPI: %s", rvw.Status.Error)
  145. }
  146. if !rvw.Status.Authenticated {
  147. return nil, errors.New("error from kubernetes TokenReviewAPI: token could not be authenticated")
  148. }
  149. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  150. return nil, errors.Wrap(err, "error parsing claims")
  151. }
  152. */
  153. }
  154. for _, pk := range p.pubKeys {
  155. if err = jwt.Claims(pk, &claims); err == nil {
  156. valid = true
  157. break
  158. }
  159. }
  160. if !valid {
  161. return nil, errs.Unauthorized("k8ssa.authorizeToken; error validating k8sSA token and extracting claims")
  162. }
  163. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  164. // more than a few minutes.
  165. if err = claims.Validate(jose.Expected{
  166. Issuer: k8sSAIssuer,
  167. }); err != nil {
  168. return nil, errs.Wrap(http.StatusUnauthorized, err, "k8ssa.authorizeToken; invalid k8sSA token claims")
  169. }
  170. if claims.Subject == "" {
  171. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA token subject cannot be empty")
  172. }
  173. return &claims, nil
  174. }
  175. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  176. // revoke the certificate with serial number in the `sub` property.
  177. func (p *K8sSA) AuthorizeRevoke(ctx context.Context, token string) error {
  178. _, err := p.authorizeToken(token, p.audiences.Revoke)
  179. return errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeRevoke")
  180. }
  181. // AuthorizeSign validates the given token.
  182. func (p *K8sSA) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  183. if _, err := p.authorizeToken(token, p.audiences.Sign); err != nil {
  184. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  185. }
  186. return []SignOption{
  187. // modifiers / withOptions
  188. newProvisionerExtensionOption(TypeK8sSA, p.Name, ""),
  189. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  190. // validators
  191. defaultPublicKeyValidator{},
  192. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  193. }, nil
  194. }
  195. // AuthorizeRenew returns an error if the renewal is disabled.
  196. func (p *K8sSA) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  197. if p.claimer.IsDisableRenewal() {
  198. return errs.Unauthorized("k8ssa.AuthorizeRenew; renew is disabled for k8sSA provisioner %s", p.GetID())
  199. }
  200. return nil
  201. }
  202. // AuthorizeSSHSign validates an request for an SSH certificate.
  203. func (p *K8sSA) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  204. if !p.claimer.IsSSHCAEnabled() {
  205. return nil, errs.Unauthorized("k8ssa.AuthorizeSSHSign; sshCA is disabled for k8sSA provisioner %s", p.GetID())
  206. }
  207. if _, err := p.authorizeToken(token, p.audiences.SSHSign); err != nil {
  208. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  209. }
  210. // Default to a user certificate with no principals if not set
  211. signOptions := []SignOption{sshCertDefaultsModifier{CertType: SSHUserCert}}
  212. return append(signOptions,
  213. // Set the default extensions.
  214. &sshDefaultExtensionModifier{},
  215. // Set the validity bounds if not set.
  216. &sshDefaultDuration{p.claimer},
  217. // Validate public key
  218. &sshDefaultPublicKeyValidator{},
  219. // Validate the validity period.
  220. &sshCertValidityValidator{p.claimer},
  221. // Require and validate all the default fields in the SSH certificate.
  222. &sshCertDefaultValidator{},
  223. ), nil
  224. }
  225. /*
  226. func checkAccess(authz kauthz.AuthorizationV1Interface) error {
  227. r := &kauthzApi.SelfSubjectAccessReview{
  228. Spec: kauthzApi.SelfSubjectAccessReviewSpec{
  229. ResourceAttributes: &kauthzApi.ResourceAttributes{
  230. Group: "authentication.k8s.io",
  231. Version: "v1",
  232. Resource: "tokenreviews",
  233. Verb: "create",
  234. },
  235. },
  236. }
  237. rvw, err := authz.SelfSubjectAccessReviews().Create(r)
  238. if err != nil {
  239. return err
  240. }
  241. if !rvw.Status.Allowed {
  242. return fmt.Errorf("Unable to create kubernetes token reviews: %s", rvw.Status.Reason)
  243. }
  244. return nil
  245. }
  246. */