k8sSA.go 8.6 KB

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