sshpop.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package provisioner
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "strconv"
  6. "time"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/db"
  9. "github.com/smallstep/cli/jose"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. // sshPOPPayload extends jwt.Claims with step attributes.
  13. type sshPOPPayload struct {
  14. jose.Claims
  15. SANs []string `json:"sans,omitempty"`
  16. Step *stepPayload `json:"step,omitempty"`
  17. sshCert *ssh.Certificate
  18. }
  19. // SSHPOP is the default provisioner, an entity that can sign tokens necessary for
  20. // signature requests.
  21. type SSHPOP struct {
  22. *base
  23. Type string `json:"type"`
  24. Name string `json:"name"`
  25. Claims *Claims `json:"claims,omitempty"`
  26. db db.AuthDB
  27. claimer *Claimer
  28. audiences Audiences
  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. return "sshpop/" + p.Name
  35. }
  36. // GetTokenID returns the identifier of the token.
  37. func (p *SSHPOP) GetTokenID(ott string) (string, error) {
  38. // Validate payload
  39. token, err := jose.ParseSigned(ott)
  40. if err != nil {
  41. return "", errors.Wrap(err, "error parsing token")
  42. }
  43. // Get claims w/out verification. We need to look up the provisioner
  44. // key in order to verify the claims and we need the issuer from the claims
  45. // before we can look up the provisioner.
  46. var claims jose.Claims
  47. if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
  48. return "", errors.Wrap(err, "error verifying claims")
  49. }
  50. return claims.ID, nil
  51. }
  52. // GetName returns the name of the provisioner.
  53. func (p *SSHPOP) GetName() string {
  54. return p.Name
  55. }
  56. // GetType returns the type of provisioner.
  57. func (p *SSHPOP) GetType() Type {
  58. return TypeSSHPOP
  59. }
  60. // GetEncryptedKey returns the base provisioner encrypted key if it's defined.
  61. func (p *SSHPOP) GetEncryptedKey() (string, string, bool) {
  62. return "", "", false
  63. }
  64. // Init initializes and validates the fields of a SSHPOP type.
  65. func (p *SSHPOP) Init(config Config) error {
  66. switch {
  67. case p.Type == "":
  68. return errors.New("provisioner type cannot be empty")
  69. case p.Name == "":
  70. return errors.New("provisioner name cannot be empty")
  71. case config.SSHKeys == nil:
  72. return errors.New("provisioner public SSH validation keys cannot be empty")
  73. }
  74. // Update claims with global ones
  75. var err error
  76. if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
  77. return err
  78. }
  79. p.audiences = config.Audiences.WithFragment(p.GetID())
  80. p.db = config.DB
  81. p.sshPubKeys = config.SSHKeys
  82. return nil
  83. }
  84. // authorizeToken performs common jwt authorization actions and returns the
  85. // claims for case specific downstream parsing.
  86. // e.g. a Sign request will auth/validate different fields than a Revoke request.
  87. func (p *SSHPOP) authorizeToken(token string, audiences []string) (*sshPOPPayload, error) {
  88. sshCert, err := ExtractSSHPOPCert(token)
  89. if err != nil {
  90. return nil, errors.Wrap(err, "authorizeToken ssh-pop")
  91. }
  92. // Check for revocation.
  93. if isRevoked, err := p.db.IsSSHRevoked(strconv.FormatUint(sshCert.Serial, 10)); err != nil {
  94. return nil, errors.Wrap(err, "authorizeToken ssh-pop")
  95. } else if isRevoked {
  96. return nil, errors.New("authorizeToken ssh-pop: ssh certificate has been revoked")
  97. }
  98. jwt, err := jose.ParseSigned(token)
  99. if err != nil {
  100. return nil, errors.Wrapf(err, "error parsing token")
  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, errors.New("sshpop certificate validAfter is in the future")
  106. }
  107. if sshCert.ValidBefore != 0 && time.Unix(int64(sshCert.ValidBefore), 0).Before(n) {
  108. return nil, errors.New("sshpop certificate validBefore is in the past")
  109. }
  110. sshCryptoPubKey, ok := sshCert.Key.(ssh.CryptoPublicKey)
  111. if !ok {
  112. return nil, errors.New("ssh 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, errors.New("error: provisioner could could not verify the sshpop header 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, errors.Wrap(err, "error parsing 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, errors.Wrapf(err, "invalid token")
  150. }
  151. // validate audiences with the defaults
  152. if !matchesAudience(claims.Audience, audiences) {
  153. return nil, errors.New("invalid token: invalid audience claim (aud)")
  154. }
  155. if claims.Subject == "" {
  156. return nil, errors.New("token subject cannot be empty")
  157. }
  158. claims.sshCert = sshCert
  159. return &claims, nil
  160. }
  161. // AuthorizeSSHRevoke validates the authorization token and extracts/validates
  162. // the SSH certificate from the ssh-pop header.
  163. func (p *SSHPOP) AuthorizeSSHRevoke(ctx context.Context, token string) error {
  164. claims, err := p.authorizeToken(token, p.audiences.SSHRevoke)
  165. if err != nil {
  166. return err
  167. }
  168. if claims.Subject != strconv.FormatUint(claims.sshCert.Serial, 10) {
  169. return errors.New("token subject must be equivalent to certificate serial number")
  170. }
  171. return err
  172. }
  173. // AuthorizeSSHRenew validates the authorization token and extracts/validates
  174. // the SSH certificate from the ssh-pop header.
  175. func (p *SSHPOP) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  176. claims, err := p.authorizeToken(token, p.audiences.SSHRenew)
  177. if err != nil {
  178. return nil, err
  179. }
  180. if claims.sshCert.CertType != ssh.HostCert {
  181. return nil, errors.New("sshpop AuthorizeSSHRenew: sshpop certificate must be a host ssh certificate")
  182. }
  183. return claims.sshCert, nil
  184. }
  185. // AuthorizeSSHRekey validates the authorization token and extracts/validates
  186. // the SSH certificate from the ssh-pop header.
  187. func (p *SSHPOP) AuthorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []SignOption, error) {
  188. claims, err := p.authorizeToken(token, p.audiences.SSHRekey)
  189. if err != nil {
  190. return nil, nil, err
  191. }
  192. if claims.sshCert.CertType != ssh.HostCert {
  193. return nil, nil, errors.New("sshpop AuthorizeSSHRekey: sshpop certificate must be a host ssh certificate")
  194. }
  195. return claims.sshCert, []SignOption{
  196. // Validate public key
  197. &sshDefaultPublicKeyValidator{},
  198. // Validate the validity period.
  199. &sshCertificateValidityValidator{p.claimer},
  200. // Require and validate all the default fields in the SSH certificate.
  201. &sshCertificateDefaultValidator{},
  202. }, nil
  203. }
  204. // ExtractSSHPOPCert parses a JWT and extracts and loads the SSH Certificate
  205. // in the sshpop header. If the header is missing, an error is returned.
  206. func ExtractSSHPOPCert(token string) (*ssh.Certificate, error) {
  207. jwt, err := jose.ParseSigned(token)
  208. if err != nil {
  209. return nil, errors.Wrapf(err, "error parsing token")
  210. }
  211. encodedSSHCert, ok := jwt.Headers[0].ExtraHeaders["sshpop"]
  212. if !ok {
  213. return nil, errors.New("token missing sshpop header")
  214. }
  215. encodedSSHCertStr, ok := encodedSSHCert.(string)
  216. if !ok {
  217. return nil, errors.New("error unexpected type for sshpop header")
  218. }
  219. sshCertBytes, err := base64.StdEncoding.DecodeString(encodedSSHCertStr)
  220. if err != nil {
  221. return nil, errors.Wrap(err, "error decoding sshpop header")
  222. }
  223. sshPub, err := ssh.ParsePublicKey(sshCertBytes)
  224. if err != nil {
  225. return nil, errors.Wrap(err, "error parsing ssh public key")
  226. }
  227. sshCert, ok := sshPub.(*ssh.Certificate)
  228. if !ok {
  229. return nil, errors.New("error converting ssh public key to ssh certificate")
  230. }
  231. return sshCert, nil
  232. }
  233. func bytesForSigning(cert *ssh.Certificate) []byte {
  234. c2 := *cert
  235. c2.Signature = nil
  236. out := c2.Marshal()
  237. // Drop trailing signature length.
  238. return out[:len(out)-4]
  239. }