sshpop.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package provisioner
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/pkg/errors"
  9. "golang.org/x/crypto/ssh"
  10. "go.step.sm/crypto/jose"
  11. "github.com/smallstep/certificates/errs"
  12. )
  13. // sshPOPPayload extends jwt.Claims with step attributes.
  14. type sshPOPPayload struct {
  15. jose.Claims
  16. SANs []string `json:"sans,omitempty"`
  17. Step *stepPayload `json:"step,omitempty"`
  18. sshCert *ssh.Certificate
  19. }
  20. // SSHPOP is the default provisioner, an entity that can sign tokens necessary for
  21. // signature requests.
  22. type SSHPOP struct {
  23. *base
  24. ID string `json:"-"`
  25. Type string `json:"type"`
  26. Name string `json:"name"`
  27. Claims *Claims `json:"claims,omitempty"`
  28. ctl *Controller
  29. sshPubKeys *SSHKeys
  30. }
  31. // GetID returns the provisioner unique identifier. The name and credential id
  32. // should uniquely identify any SSH-POP provisioner.
  33. func (p *SSHPOP) GetID() string {
  34. if p.ID != "" {
  35. return p.ID
  36. }
  37. return p.GetIDForToken()
  38. }
  39. // GetIDForToken returns an identifier that will be used to load the provisioner
  40. // from a token.
  41. func (p *SSHPOP) GetIDForToken() string {
  42. return "sshpop/" + p.Name
  43. }
  44. // GetTokenID returns the identifier of the token.
  45. func (p *SSHPOP) GetTokenID(ott string) (string, error) {
  46. // Validate payload
  47. token, err := jose.ParseSigned(ott)
  48. if err != nil {
  49. return "", errors.Wrap(err, "error parsing token")
  50. }
  51. // Get claims w/out verification. We need to look up the provisioner
  52. // key in order to verify the claims and we need the issuer from the claims
  53. // before we can look up the provisioner.
  54. var claims jose.Claims
  55. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  56. return "", errors.Wrap(err, "error verifying claims")
  57. }
  58. return claims.ID, nil
  59. }
  60. // GetName returns the name of the provisioner.
  61. func (p *SSHPOP) GetName() string {
  62. return p.Name
  63. }
  64. // GetType returns the type of provisioner.
  65. func (p *SSHPOP) GetType() Type {
  66. return TypeSSHPOP
  67. }
  68. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  69. func (p *SSHPOP) GetEncryptedKey() (string, string, bool) {
  70. return "", "", false
  71. }
  72. // Init initializes and validates the fields of a SSHPOP type.
  73. func (p *SSHPOP) Init(config Config) (err error) {
  74. switch {
  75. case p.Type == "":
  76. return errors.New("provisioner type cannot be empty")
  77. case p.Name == "":
  78. return errors.New("provisioner name cannot be empty")
  79. case config.SSHKeys == nil:
  80. return errors.New("provisioner public SSH validation keys cannot be empty")
  81. }
  82. p.sshPubKeys = config.SSHKeys
  83. config.Audiences = config.Audiences.WithFragment(p.GetIDForToken())
  84. p.ctl, err = NewController(p, p.Claims, config, nil)
  85. return
  86. }
  87. // authorizeToken performs common jwt authorization actions and returns the
  88. // claims for case specific downstream parsing.
  89. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  90. //
  91. // Checking for certificate revocation has been moved to the authority package.
  92. func (p *SSHPOP) authorizeToken(token string, audiences []string, checkValidity bool) (*sshPOPPayload, error) {
  93. sshCert, jwt, err := ExtractSSHPOPCert(token)
  94. if err != nil {
  95. return nil, errs.Wrap(http.StatusUnauthorized, err,
  96. "sshpop.authorizeToken; error extracting sshpop header from token")
  97. }
  98. // Check validity period of the certificate.
  99. //
  100. // Controller.AuthorizeSSHRenew will validate this on the renewal flow.
  101. if checkValidity {
  102. unixNow := time.Now().Unix()
  103. if after := int64(sshCert.ValidAfter); after < 0 || unixNow < int64(sshCert.ValidAfter) {
  104. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validAfter is in the future")
  105. }
  106. if before := int64(sshCert.ValidBefore); sshCert.ValidBefore != uint64(ssh.CertTimeInfinity) && (unixNow >= before || before < 0) {
  107. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validBefore is in the past")
  108. }
  109. }
  110. sshCryptoPubKey, ok := sshCert.Key.(ssh.CryptoPublicKey)
  111. if !ok {
  112. return nil, errs.InternalServer("sshpop.authorizeToken; sshpop public key could not be cast to ssh CryptoPublicKey")
  113. }
  114. pubKey := sshCryptoPubKey.CryptoPublicKey()
  115. var (
  116. found bool
  117. data = bytesForSigning(sshCert)
  118. keys []ssh.PublicKey
  119. )
  120. if sshCert.CertType == ssh.UserCert {
  121. keys = p.sshPubKeys.UserKeys
  122. } else {
  123. keys = p.sshPubKeys.HostKeys
  124. }
  125. for _, k := range keys {
  126. if err = (&ssh.Certificate{Key: k}).Verify(data, sshCert.Signature); err == nil {
  127. found = true
  128. break
  129. }
  130. }
  131. if !found {
  132. return nil, errs.Unauthorized("sshpop.authorizeToken; could not find valid ca signer to verify sshpop certificate")
  133. }
  134. // Using the ssh certificates key to validate the claims accomplishes two
  135. // things:
  136. // 1. Asserts that the private key used to sign the token corresponds
  137. // to the public certificate in the `sshpop` header of the token.
  138. // 2. Asserts that the claims are valid - have not been tampered with.
  139. var claims sshPOPPayload
  140. if err = jwt.Claims(pubKey, &claims); err != nil {
  141. return nil, errs.Wrap(http.StatusUnauthorized, err, "sshpop.authorizeToken; error parsing sshpop token claims")
  142. }
  143. // According to "rfc7519 JSON Web Token" acceptable skew should be no
  144. // more than a few minutes.
  145. if err = claims.ValidateWithLeeway(jose.Expected{
  146. Issuer: p.Name,
  147. Time: time.Now().UTC(),
  148. }, time.Minute); err != nil {
  149. return nil, errs.Wrap(http.StatusUnauthorized, err, "sshpop.authorizeToken; invalid sshpop token")
  150. }
  151. // validate audiences with the defaults
  152. if !matchesAudience(claims.Audience, audiences) {
  153. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop token has invalid audience "+
  154. "claim (aud): expected %s, but got %s", audiences, claims.Audience)
  155. }
  156. if claims.Subject == "" {
  157. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop token subject cannot be empty")
  158. }
  159. claims.sshCert = sshCert
  160. return &claims, nil
  161. }
  162. // AuthorizeSSHRevoke validates the authorization token and extracts/validates
  163. // the SSH certificate from the ssh-pop header.
  164. func (p *SSHPOP) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  165. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHRevoke, true)
  166. if err != nil {
  167. return errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRevoke")
  168. }
  169. if claims.Subject != strconv.FormatUint(claims.sshCert.Serial, 10) {
  170. return errs.BadRequest("sshpop token subject must be equivalent to sshpop certificate serial number")
  171. }
  172. return nil
  173. }
  174. // AuthorizeSSHRenew validates the authorization token and extracts/validates
  175. // the SSH certificate from the ssh-pop header.
  176. func (p *SSHPOP) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  177. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHRenew, false)
  178. if err != nil {
  179. return nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRenew")
  180. }
  181. if claims.sshCert.CertType != ssh.HostCert {
  182. return nil, errs.BadRequest("sshpop certificate must be a host ssh certificate")
  183. }
  184. return claims.sshCert, p.ctl.AuthorizeSSHRenew(ctx, claims.sshCert)
  185. }
  186. // AuthorizeSSHRekey validates the authorization token and extracts/validates
  187. // the SSH certificate from the ssh-pop header.
  188. func (p *SSHPOP) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  189. claims, err := p.authorizeToken(token, p.ctl.Audiences.SSHRekey, true)
  190. if err != nil {
  191. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRekey")
  192. }
  193. if claims.sshCert.CertType != ssh.HostCert {
  194. return nil, nil, errs.BadRequest("sshpop certificate must be a host ssh certificate")
  195. }
  196. return claims.sshCert, []SignOption{
  197. // Validate public key
  198. &sshDefaultPublicKeyValidator{},
  199. // Validate the validity period.
  200. &sshCertValidityValidator{p.ctl.Claimer},
  201. // Require and validate all the default fields in the SSH certificate.
  202. &sshCertDefaultValidator{},
  203. }, nil
  204. }
  205. // ExtractSSHPOPCert parses a JWT and extracts and loads the SSH Certificate
  206. // in the sshpop header. If the header is missing, an error is returned.
  207. func ExtractSSHPOPCert(token string) (*ssh.Certificate, *jose.JSONWebToken, error) {
  208. jwt, err := jose.ParseSigned(token)
  209. if err != nil {
  210. return nil, nil, errors.Wrapf(err, "extractSSHPOPCert; error parsing token")
  211. }
  212. encodedSSHCert, ok := jwt.Headers[0].ExtraHeaders["sshpop"]
  213. if !ok {
  214. return nil, nil, errors.New("extractSSHPOPCert; token missing sshpop header")
  215. }
  216. encodedSSHCertStr, ok := encodedSSHCert.(string)
  217. if !ok {
  218. return nil, nil, errors.Errorf("extractSSHPOPCert; error unexpected type for sshpop header: "+
  219. "want 'string', but got '%T'", encodedSSHCert)
  220. }
  221. sshCertBytes, err := base64.StdEncoding.DecodeString(encodedSSHCertStr)
  222. if err != nil {
  223. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error base64 decoding sshpop header")
  224. }
  225. sshPub, err := ssh.ParsePublicKey(sshCertBytes)
  226. if err != nil {
  227. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error parsing ssh public key")
  228. }
  229. sshCert, ok := sshPub.(*ssh.Certificate)
  230. if !ok {
  231. return nil, nil, errors.New("extractSSHPOPCert; error converting ssh public key to ssh certificate")
  232. }
  233. return sshCert, jwt, nil
  234. }
  235. func bytesForSigning(cert *ssh.Certificate) []byte {
  236. c2 := *cert
  237. c2.Signature = nil
  238. out := c2.Marshal()
  239. // Drop trailing signature length.
  240. return out[:len(out)-4]
  241. }