k8sSA.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. "go.step.sm/crypto/jose"
  12. "go.step.sm/crypto/pemutil"
  13. "go.step.sm/crypto/sshutil"
  14. "go.step.sm/crypto/x509util"
  15. "go.step.sm/linkedca"
  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(ott string) (string, error) {
  65. return "", errors.New("not implemented")
  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. jwt, err := jose.ParseSigned(token)
  133. if err != nil {
  134. return nil, errs.Wrap(http.StatusUnauthorized, err,
  135. "k8ssa.authorizeToken; error parsing k8sSA token")
  136. }
  137. var (
  138. valid bool
  139. claims k8sSAPayload
  140. )
  141. if p.pubKeys == nil {
  142. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA TokenReview API integration not implemented")
  143. /* NOTE: We plan to support the TokenReview API in a future release.
  144. Below is some code that should be useful when we prioritize
  145. this integration.
  146. tr := kauthnApi.TokenReview{Spec: kauthnApi.TokenReviewSpec{Token: string(token)}}
  147. rvw, err := p.kauthn.TokenReviews().Create(&tr)
  148. if err != nil {
  149. return nil, errors.Wrap(err, "error using kubernetes TokenReview API")
  150. }
  151. if rvw.Status.Error != "" {
  152. return nil, errors.Errorf("error from kubernetes TokenReviewAPI: %s", rvw.Status.Error)
  153. }
  154. if !rvw.Status.Authenticated {
  155. return nil, errors.New("error from kubernetes TokenReviewAPI: token could not be authenticated")
  156. }
  157. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  158. return nil, errors.Wrap(err, "error parsing claims")
  159. }
  160. */
  161. }
  162. for _, pk := range p.pubKeys {
  163. if err = jwt.Claims(pk, &claims); err == nil {
  164. valid = true
  165. break
  166. }
  167. }
  168. if !valid {
  169. return nil, errs.Unauthorized("k8ssa.authorizeToken; error validating k8sSA token and extracting claims")
  170. }
  171. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  172. // more than a few minutes.
  173. if err = claims.Validate(jose.Expected{
  174. Issuer: k8sSAIssuer,
  175. }); err != nil {
  176. return nil, errs.Wrap(http.StatusUnauthorized, err, "k8ssa.authorizeToken; invalid k8sSA token claims")
  177. }
  178. if claims.Subject == "" {
  179. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA token subject cannot be empty")
  180. }
  181. return &claims, nil
  182. }
  183. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  184. // revoke the certificate with serial number in the `sub` property.
  185. func (p *K8sSA) AuthorizeRevoke(ctx context.Context, token string) error {
  186. _, err := p.authorizeToken(token, p.ctl.Audiences.Revoke)
  187. return errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeRevoke")
  188. }
  189. // AuthorizeSign validates the given token.
  190. func (p *K8sSA) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  191. claims, err := p.authorizeToken(token, p.ctl.Audiences.Sign)
  192. if err != nil {
  193. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  194. }
  195. // Add some values to use in custom templates.
  196. data := x509util.NewTemplateData()
  197. data.SetCommonName(claims.ServiceAccountName)
  198. if v, err := unsafeParseSigned(token); err == nil {
  199. data.SetToken(v)
  200. }
  201. // Certificate templates: on K8sSA the default template is the certificate
  202. // request.
  203. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultAdminLeafTemplate)
  204. if err != nil {
  205. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  206. }
  207. return []SignOption{
  208. p,
  209. templateOptions,
  210. // modifiers / withOptions
  211. newProvisionerExtensionOption(TypeK8sSA, p.Name, ""),
  212. profileDefaultDuration(p.ctl.Claimer.DefaultTLSCertDuration()),
  213. // validators
  214. defaultPublicKeyValidator{},
  215. newValidityValidator(p.ctl.Claimer.MinTLSCertDuration(), p.ctl.Claimer.MaxTLSCertDuration()),
  216. newX509NamePolicyValidator(p.ctl.getPolicy().getX509()),
  217. p.ctl.newWebhookController(data, linkedca.Webhook_X509),
  218. }, nil
  219. }
  220. // AuthorizeRenew returns an error if the renewal is disabled.
  221. func (p *K8sSA) AuthorizeRenew(ctx context.Context, cert *x509.Certificate) error {
  222. return p.ctl.AuthorizeRenew(ctx, cert)
  223. }
  224. // AuthorizeSSHSign validates an request for an SSH certificate.
  225. func (p *K8sSA) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  226. if !p.ctl.Claimer.IsSSHCAEnabled() {
  227. return nil, errs.Unauthorized("k8ssa.AuthorizeSSHSign; sshCA is disabled for k8sSA provisioner '%s'", p.GetName())
  228. }
  229. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHSign)
  230. if err != nil {
  231. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  232. }
  233. // Certificate templates.
  234. // Set some default variables to be used in the templates.
  235. data := sshutil.CreateTemplateData(sshutil.HostCert, claims.ServiceAccountName, []string{claims.ServiceAccountName})
  236. if v, err := unsafeParseSigned(token); err == nil {
  237. data.SetToken(v)
  238. }
  239. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.CertificateRequestTemplate)
  240. if err != nil {
  241. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  242. }
  243. signOptions := []SignOption{templateOptions}
  244. return append(signOptions,
  245. p,
  246. // Require type, key-id and principals in the SignSSHOptions.
  247. &sshCertOptionsRequireValidator{CertType: true, KeyID: true, Principals: true},
  248. // Set the validity bounds if not set.
  249. &sshDefaultDuration{p.ctl.Claimer},
  250. // Validate public key
  251. &sshDefaultPublicKeyValidator{},
  252. // Validate the validity period.
  253. &sshCertValidityValidator{p.ctl.Claimer},
  254. // Require and validate all the default fields in the SSH certificate.
  255. &sshCertDefaultValidator{},
  256. // Ensure that all principal names are allowed
  257. newSSHNamePolicyValidator(p.ctl.getPolicy().getSSHHost(), p.ctl.getPolicy().getSSHUser()),
  258. // Call webhooks
  259. p.ctl.newWebhookController(data, linkedca.Webhook_SSH),
  260. ), nil
  261. }
  262. /*
  263. func checkAccess(authz kauthz.AuthorizationV1Interface) error {
  264. r := &kauthzApi.SelfSubjectAccessReview{
  265. Spec: kauthzApi.SelfSubjectAccessReviewSpec{
  266. ResourceAttributes: &kauthzApi.ResourceAttributes{
  267. Group: "authentication.k8s.io",
  268. Version: "v1",
  269. Resource: "tokenreviews",
  270. Verb: "create",
  271. },
  272. },
  273. }
  274. rvw, err := authz.SelfSubjectAccessReviews().Create(r)
  275. if err != nil {
  276. return err
  277. }
  278. if !rvw.Status.Allowed {
  279. return fmt.Errorf("Unable to create kubernetes token reviews: %s", rvw.Status.Reason)
  280. }
  281. return nil
  282. }
  283. */