k8sSA.go 10 KB

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