sshpop.go 8.1 KB

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