4
0

sshpop.go 9.3 KB

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