4
0

sshpop.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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/errs"
  10. "go.step.sm/crypto/jose"
  11. "golang.org/x/crypto/ssh"
  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. claimer *Claimer
  29. audiences Audiences
  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) 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. // Update claims with global ones
  84. var err error
  85. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  86. return err
  87. }
  88. p.audiences = config.Audiences.WithFragment(p.GetIDForToken())
  89. p.sshPubKeys = config.SSHKeys
  90. return nil
  91. }
  92. // authorizeToken performs common jwt authorization actions and returns the
  93. // claims for case specific downstream parsing.
  94. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  95. //
  96. // Checking for certificate revocation has been moved to the authority package.
  97. func (p *SSHPOP) authorizeToken(token string, audiences []string) (*sshPOPPayload, error) {
  98. sshCert, jwt, err := ExtractSSHPOPCert(token)
  99. if err != nil {
  100. return nil, errs.Wrap(http.StatusUnauthorized, err,
  101. "sshpop.authorizeToken; error extracting sshpop header from token")
  102. }
  103. // Check validity period of the certificate.
  104. n := time.Now()
  105. if sshCert.ValidAfter != 0 && time.Unix(int64(sshCert.ValidAfter), 0).After(n) {
  106. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validAfter is in the future")
  107. }
  108. if sshCert.ValidBefore != 0 && time.Unix(int64(sshCert.ValidBefore), 0).Before(n) {
  109. return nil, errs.Unauthorized("sshpop.authorizeToken; sshpop certificate validBefore is in the past")
  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(ctx context.Context, token string) error {
  166. claims, err := p.authorizeToken(token, p.audiences.SSHRevoke)
  167. if err != nil {
  168. return errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRevoke")
  169. }
  170. if claims.Subject != strconv.FormatUint(claims.sshCert.Serial, 10) {
  171. return errs.BadRequest("sshpop.AuthorizeSSHRevoke; sshpop token subject " +
  172. "must be equivalent to sshpop certificate serial number")
  173. }
  174. return nil
  175. }
  176. // AuthorizeSSHRenew validates the authorization token and extracts/validates
  177. // the SSH certificate from the ssh-pop header.
  178. func (p *SSHPOP) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  179. claims, err := p.authorizeToken(token, p.audiences.SSHRenew)
  180. if err != nil {
  181. return nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRenew")
  182. }
  183. if claims.sshCert.CertType != ssh.HostCert {
  184. return nil, errs.BadRequest("sshpop.AuthorizeSSHRenew; sshpop certificate must be a host ssh certificate")
  185. }
  186. return claims.sshCert, nil
  187. }
  188. // AuthorizeSSHRekey validates the authorization token and extracts/validates
  189. // the SSH certificate from the ssh-pop header.
  190. func (p *SSHPOP) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  191. claims, err := p.authorizeToken(token, p.audiences.SSHRekey)
  192. if err != nil {
  193. return nil, nil, errs.Wrap(http.StatusInternalServerError, err, "sshpop.AuthorizeSSHRekey")
  194. }
  195. if claims.sshCert.CertType != ssh.HostCert {
  196. return nil, nil, errs.BadRequest("sshpop.AuthorizeSSHRekey; sshpop certificate must be a host ssh certificate")
  197. }
  198. return claims.sshCert, []SignOption{
  199. // Validate public key
  200. &sshDefaultPublicKeyValidator{},
  201. // Validate the validity period.
  202. &sshCertValidityValidator{p.claimer},
  203. // Require and validate all the default fields in the SSH certificate.
  204. &sshCertDefaultValidator{},
  205. }, nil
  206. }
  207. // ExtractSSHPOPCert parses a JWT and extracts and loads the SSH Certificate
  208. // in the sshpop header. If the header is missing, an error is returned.
  209. func ExtractSSHPOPCert(token string) (*ssh.Certificate, *jose.JSONWebToken, error) {
  210. jwt, err := jose.ParseSigned(token)
  211. if err != nil {
  212. return nil, nil, errors.Wrapf(err, "extractSSHPOPCert; error parsing token")
  213. }
  214. encodedSSHCert, ok := jwt.Headers[0].ExtraHeaders["sshpop"]
  215. if !ok {
  216. return nil, nil, errors.New("extractSSHPOPCert; token missing sshpop header")
  217. }
  218. encodedSSHCertStr, ok := encodedSSHCert.(string)
  219. if !ok {
  220. return nil, nil, errors.Errorf("extractSSHPOPCert; error unexpected type for sshpop header: "+
  221. "want 'string', but got '%T'", encodedSSHCert)
  222. }
  223. sshCertBytes, err := base64.StdEncoding.DecodeString(encodedSSHCertStr)
  224. if err != nil {
  225. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error base64 decoding sshpop header")
  226. }
  227. sshPub, err := ssh.ParsePublicKey(sshCertBytes)
  228. if err != nil {
  229. return nil, nil, errors.Wrap(err, "extractSSHPOPCert; error parsing ssh public key")
  230. }
  231. sshCert, ok := sshPub.(*ssh.Certificate)
  232. if !ok {
  233. return nil, nil, errors.New("extractSSHPOPCert; error converting ssh public key to ssh certificate")
  234. }
  235. return sshCert, jwt, nil
  236. }
  237. func bytesForSigning(cert *ssh.Certificate) []byte {
  238. c2 := *cert
  239. c2.Signature = nil
  240. out := c2.Marshal()
  241. // Drop trailing signature length.
  242. return out[:len(out)-4]
  243. }