sshpop.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. package provisioner
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/db"
  10. "github.com/smallstep/certificates/errs"
  11. "go.step.sm/crypto/jose"
  12. "golang.org/x/crypto/ssh"
  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. Type string `json:"type"`
  26. Name string `json:"name"`
  27. Claims *Claims `json:"claims,omitempty"`
  28. db db.AuthDB
  29. claimer *Claimer
  30. audiences Audiences
  31. sshPubKeys *SSHKeys
  32. }
  33. // GetID returns the provisioner unique identifier. The name and credential id
  34. // should uniquely identify any SSH-POP provisioner.
  35. func (p *SSHPOP) GetID() string {
  36. return "sshpop/" + p.Name
  37. }
  38. // GetTokenID returns the identifier of the token.
  39. func (p *SSHPOP) GetTokenID(ott string) (string, error) {
  40. // Validate payload
  41. token, err := jose.ParseSigned(ott)
  42. if err != nil {
  43. return "", errors.Wrap(err, "error parsing token")
  44. }
  45. // Get claims w/out verification. We need to look up the provisioner
  46. // key in order to verify the claims and we need the issuer from the claims
  47. // before we can look up the provisioner.
  48. var claims jose.Claims
  49. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  50. return "", errors.Wrap(err, "error verifying claims")
  51. }
  52. return claims.ID, nil
  53. }
  54. // GetName returns the name of the provisioner.
  55. func (p *SSHPOP) GetName() string {
  56. return p.Name
  57. }
  58. // GetType returns the type of provisioner.
  59. func (p *SSHPOP) GetType() Type {
  60. return TypeSSHPOP
  61. }
  62. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  63. func (p *SSHPOP) GetEncryptedKey() (string, string, bool) {
  64. return "", "", false
  65. }
  66. // Init initializes and validates the fields of a SSHPOP type.
  67. func (p *SSHPOP) Init(config Config) error {
  68. switch {
  69. case p.Type == "":
  70. return errors.New("provisioner type cannot be empty")
  71. case p.Name == "":
  72. return errors.New("provisioner name cannot be empty")
  73. case config.SSHKeys == nil:
  74. return errors.New("provisioner public SSH validation keys cannot be empty")
  75. }
  76. // Update claims with global ones
  77. var err error
  78. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  79. return err
  80. }
  81. p.audiences = config.Audiences.WithFragment(p.GetID())
  82. p.db = config.DB
  83. p.sshPubKeys = config.SSHKeys
  84. return nil
  85. }
  86. // authorizeToken performs common jwt authorization actions and returns the
  87. // claims for case specific downstream parsing.
  88. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  89. func (p *SSHPOP) authorizeToken(token string, audiences []string) (*sshPOPPayload, error) {
  90. sshCert, jwt, err := ExtractSSHPOPCert(token)
  91. if err != nil {
  92. return nil, errs.Wrap(http.StatusUnauthorized, err,
  93. "sshpop.authorizeToken; error extracting sshpop header from token")
  94. }
  95. // Check for revocation.
  96. if isRevoked, err := p.db.IsSSHRevoked(strconv.FormatUint(sshCert.Serial, 10)); err != nil {
  97. return nil, errs.Wrap(http.StatusInternalServerError, err,
  98. "sshpop.authorizeToken; error checking checking sshpop cert revocation")
  99. } else if isRevoked {
  100. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate is revoked")
  101. }
  102. // Check validity period of the certificate.
  103. n := time.Now()
  104. if sshCert.ValidAfter != 0 && time.Unix(int64(sshCert.ValidAfter), 0).After(n) {
  105. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validAfter is in the future")
  106. }
  107. if sshCert.ValidBefore != 0 && time.Unix(int64(sshCert.ValidBefore), 0).Before(n) {
  108. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validBefore is in the past")
  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.audiences.SSHRevoke)
  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.AuthorizeSSHRevoke; sshpop token subject " +
  171. "must be equivalent to sshpop certificate serial number")
  172. }
  173. return nil
  174. }
  175. // AuthorizeSSHRenew validates the authorization token and extracts/validates
  176. // the SSH certificate from the ssh-pop header.
  177. func (p *SSHPOP) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  178. claims, err := p.authorizeToken(token, p.audiences.SSHRenew)
  179. if err != nil {
  180. return nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRenew")
  181. }
  182. if claims.sshCert.CertType != ssh.HostCert {
  183. return nil, errs.BadRequest("sshpop.AuthorizeSSHRenew; sshpop certificate must be a host ssh certificate")
  184. }
  185. return claims.sshCert, nil
  186. }
  187. // AuthorizeSSHRekey validates the authorization token and extracts/validates
  188. // the SSH certificate from the ssh-pop header.
  189. func (p *SSHPOP) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  190. claims, err := p.authorizeToken(token, p.audiences.SSHRekey)
  191. if err != nil {
  192. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRekey")
  193. }
  194. if claims.sshCert.CertType != ssh.HostCert {
  195. return nil, nil, errs.BadRequest("sshpop.AuthorizeSSHRekey; sshpop certificate must be a host ssh certificate")
  196. }
  197. return claims.sshCert, []SignOption{
  198. // Validate public key
  199. &sshDefaultPublicKeyValidator{},
  200. // Validate the validity period.
  201. &sshCertValidityValidator{p.claimer},
  202. // Require and validate all the default fields in the SSH certificate.
  203. &sshCertDefaultValidator{},
  204. }, nil
  205. }
  206. // ExtractSSHPOPCert parses a JWT and extracts and loads the SSH Certificate
  207. // in the sshpop header. If the header is missing, an error is returned.
  208. func ExtractSSHPOPCert(token string) (*ssh.Certificate, *jose.JSONWebToken, error) {
  209. jwt, err := jose.ParseSigned(token)
  210. if err != nil {
  211. return nil, nil, errors.Wrapf(err, "extractSSHPOPCert; error parsing token")
  212. }
  213. encodedSSHCert, ok := jwt.Headers[0].ExtraHeaders["sshpop"]
  214. if !ok {
  215. return nil, nil, errors.New("extractSSHPOPCert; token missing sshpop header")
  216. }
  217. encodedSSHCertStr, ok := encodedSSHCert.(string)
  218. if !ok {
  219. return nil, nil, errors.Errorf("extractSSHPOPCert; error unexpected type for sshpop header: "+
  220. "want 'string', but got '%T'", encodedSSHCert)
  221. }
  222. sshCertBytes, err := base64.StdEncoding.DecodeString(encodedSSHCertStr)
  223. if err != nil {
  224. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error base64 decoding sshpop header")
  225. }
  226. sshPub, err := ssh.ParsePublicKey(sshCertBytes)
  227. if err != nil {
  228. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error parsing ssh public key")
  229. }
  230. sshCert, ok := sshPub.(*ssh.Certificate)
  231. if !ok {
  232. return nil, nil, errors.New("extractSSHPOPCert; error converting ssh public key to ssh certificate")
  233. }
  234. return sshCert, jwt, nil
  235. }
  236. func bytesForSigning(cert *ssh.Certificate) []byte {
  237. c2 := *cert
  238. c2.Signature = nil
  239. out := c2.Marshal()
  240. // Drop trailing signature length.
  241. return out[:len(out)-4]
  242. }