k8sSA.go 11 KB

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