k8sSA.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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/certificates/errs"
  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. )
  17. // NOTE: There can be at most one kubernetes service account provisioner configured
  18. // per instance of step-ca. This is due to a lack of distinguishing information
  19. // contained in kubernetes service account tokens.
  20. const (
  21. // K8sSAName is the default name used for kubernetes service account provisioners.
  22. K8sSAName = "k8sSA-default"
  23. // K8sSAID is the default ID for kubernetes service account provisioners.
  24. K8sSAID = "k8ssa/" + K8sSAName
  25. k8sSAIssuer = "kubernetes/serviceaccount"
  26. )
  27. // jwtPayload extends jwt.Claims with step attributes.
  28. type k8sSAPayload struct {
  29. jose.Claims
  30. Namespace string `json:"kubernetes.io/serviceaccount/namespace,omitempty"`
  31. SecretName string `json:"kubernetes.io/serviceaccount/secret.name,omitempty"`
  32. ServiceAccountName string `json:"kubernetes.io/serviceaccount/service-account.name,omitempty"`
  33. ServiceAccountUID string `json:"kubernetes.io/serviceaccount/service-account.uid,omitempty"`
  34. }
  35. // K8sSA represents a Kubernetes ServiceAccount provisioner; an
  36. // entity trusted to make signature requests.
  37. type K8sSA struct {
  38. *base
  39. ID string `json:"-"`
  40. Type string `json:"type"`
  41. Name string `json:"name"`
  42. PubKeys []byte `json:"publicKeys,omitempty"`
  43. Claims *Claims `json:"claims,omitempty"`
  44. Options *Options `json:"options,omitempty"`
  45. claimer *Claimer
  46. audiences Audiences
  47. //kauthn kauthn.AuthenticationV1Interface
  48. pubKeys []interface{}
  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. // Update claims with global ones
  126. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  127. return err
  128. }
  129. p.audiences = config.Audiences
  130. return err
  131. }
  132. // authorizeToken performs common jwt authorization actions and returns the
  133. // claims for case specific downstream parsing.
  134. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  135. func (p *K8sSA) authorizeToken(token string, audiences []string) (*k8sSAPayload, error) {
  136. jwt, err := jose.ParseSigned(token)
  137. if err != nil {
  138. return nil, errs.Wrap(http.StatusUnauthorized, err,
  139. "k8ssa.authorizeToken; error parsing k8sSA token")
  140. }
  141. var (
  142. valid bool
  143. claims k8sSAPayload
  144. )
  145. if p.pubKeys == nil {
  146. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA TokenReview API integration not implemented")
  147. /* NOTE: We plan to support the TokenReview API in a future release.
  148. Below is some code that should be useful when we prioritize
  149. this integration.
  150. tr := kauthnApi.TokenReview{Spec: kauthnApi.TokenReviewSpec{Token: string(token)}}
  151. rvw, err := p.kauthn.TokenReviews().Create(&tr)
  152. if err != nil {
  153. return nil, errors.Wrap(err, "error using kubernetes TokenReview API")
  154. }
  155. if rvw.Status.Error != "" {
  156. return nil, errors.Errorf("error from kubernetes TokenReviewAPI: %s", rvw.Status.Error)
  157. }
  158. if !rvw.Status.Authenticated {
  159. return nil, errors.New("error from kubernetes TokenReviewAPI: token could not be authenticated")
  160. }
  161. if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
  162. return nil, errors.Wrap(err, "error parsing claims")
  163. }
  164. */
  165. }
  166. for _, pk := range p.pubKeys {
  167. if err = jwt.Claims(pk, &claims); err == nil {
  168. valid = true
  169. break
  170. }
  171. }
  172. if !valid {
  173. return nil, errs.Unauthorized("k8ssa.authorizeToken; error validating k8sSA token and extracting claims")
  174. }
  175. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  176. // more than a few minutes.
  177. if err = claims.Validate(jose.Expected{
  178. Issuer: k8sSAIssuer,
  179. }); err != nil {
  180. return nil, errs.Wrap(http.StatusUnauthorized, err, "k8ssa.authorizeToken; invalid k8sSA token claims")
  181. }
  182. if claims.Subject == "" {
  183. return nil, errs.Unauthorized("k8ssa.authorizeToken; k8sSA token subject cannot be empty")
  184. }
  185. return &claims, nil
  186. }
  187. // AuthorizeRevoke returns an error if the provisioner does not have rights to
  188. // revoke the certificate with serial number in the `sub` property.
  189. func (p *K8sSA) AuthorizeRevoke(ctx context.Context, token string) error {
  190. _, err := p.authorizeToken(token, p.audiences.Revoke)
  191. return errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeRevoke")
  192. }
  193. // AuthorizeSign validates the given token.
  194. func (p *K8sSA) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
  195. claims, err := p.authorizeToken(token, p.audiences.Sign)
  196. if err != nil {
  197. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  198. }
  199. // Add some values to use in custom templates.
  200. data := x509util.NewTemplateData()
  201. data.SetCommonName(claims.ServiceAccountName)
  202. if v, err := unsafeParseSigned(token); err == nil {
  203. data.SetToken(v)
  204. }
  205. // Certificate templates: on K8sSA the default template is the certificate
  206. // request.
  207. templateOptions, err := CustomTemplateOptions(p.Options, data, x509util.DefaultAdminLeafTemplate)
  208. if err != nil {
  209. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSign")
  210. }
  211. return []SignOption{
  212. templateOptions,
  213. // modifiers / withOptions
  214. newProvisionerExtensionOption(TypeK8sSA, p.Name, ""),
  215. profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
  216. // validators
  217. defaultPublicKeyValidator{},
  218. newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
  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. if p.claimer.IsDisableRenewal() {
  224. return errs.Unauthorized("k8ssa.AuthorizeRenew; renew is disabled for k8sSA provisioner '%s'", p.GetName())
  225. }
  226. return nil
  227. }
  228. // AuthorizeSSHSign validates an request for an SSH certificate.
  229. func (p *K8sSA) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption, error) {
  230. if !p.claimer.IsSSHCAEnabled() {
  231. return nil, errs.Unauthorized("k8ssa.AuthorizeSSHSign; sshCA is disabled for k8sSA provisioner '%s'", p.GetName())
  232. }
  233. claims, err := p.authorizeToken(token, p.audiences.SSHSign)
  234. if err != nil {
  235. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  236. }
  237. // Certificate templates.
  238. // Set some default variables to be used in the templates.
  239. data := sshutil.CreateTemplateData(sshutil.HostCert, claims.ServiceAccountName, []string{claims.ServiceAccountName})
  240. if v, err := unsafeParseSigned(token); err == nil {
  241. data.SetToken(v)
  242. }
  243. templateOptions, err := CustomSSHTemplateOptions(p.Options, data, sshutil.CertificateRequestTemplate)
  244. if err != nil {
  245. return nil, errs.Wrap(http.StatusInternalServerError, err, "k8ssa.AuthorizeSSHSign")
  246. }
  247. signOptions := []SignOption{templateOptions}
  248. return append(signOptions,
  249. // Require type, key-id and principals in the SignSSHOptions.
  250. &sshCertOptionsRequireValidator{CertType: true, KeyID: true, Principals: true},
  251. // Set the validity bounds if not set.
  252. &sshDefaultDuration{p.claimer},
  253. // Validate public key
  254. &sshDefaultPublicKeyValidator{},
  255. // Validate the validity period.
  256. &sshCertValidityValidator{p.claimer},
  257. // Require and validate all the default fields in the SSH certificate.
  258. &sshCertDefaultValidator{},
  259. ), nil
  260. }
  261. /*
  262. func checkAccess(authz kauthz.AuthorizationV1Interface) error {
  263. r := &kauthzApi.SelfSubjectAccessReview{
  264. Spec: kauthzApi.SelfSubjectAccessReviewSpec{
  265. ResourceAttributes: &kauthzApi.ResourceAttributes{
  266. Group: "authentication.k8s.io",
  267. Version: "v1",
  268. Resource: "tokenreviews",
  269. Verb: "create",
  270. },
  271. },
  272. }
  273. rvw, err := authz.SelfSubjectAccessReviews().Create(r)
  274. if err != nil {
  275. return err
  276. }
  277. if !rvw.Status.Allowed {
  278. return fmt.Errorf("Unable to create kubernetes token reviews: %s", rvw.Status.Reason)
  279. }
  280. return nil
  281. }
  282. */