ssh.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package api
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "net/http"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/authority"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. // SSHAuthority is the interface implemented by a SSH CA authority.
  13. type SSHAuthority interface {
  14. SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  15. SignSSHAddUser(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  16. SSHConfig() (*authority.SSHConfiguration, error)
  17. }
  18. // SignSSHRequest is the request body of an SSH certificate request.
  19. type SignSSHRequest struct {
  20. PublicKey []byte `json:"publicKey"` //base64 encoded
  21. OTT string `json:"ott"`
  22. CertType string `json:"certType,omitempty"`
  23. Principals []string `json:"principals,omitempty"`
  24. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  25. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  26. AddUserPublicKey []byte `json:"addUserPublicKey,omitempty"`
  27. }
  28. // SignSSHResponse is the response object that returns the SSH certificate.
  29. type SignSSHResponse struct {
  30. Certificate SSHCertificate `json:"crt"`
  31. AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
  32. }
  33. // SSHConfigResponse represents the response object that returns the SSH user
  34. // and host keys.
  35. type SSHConfigResponse struct {
  36. UserKey *SSHPublicKey `json:"userKey,omitempty"`
  37. HostKey *SSHPublicKey `json:"hostKey,omitempty"`
  38. }
  39. // SSHCertificate represents the response SSH certificate.
  40. type SSHCertificate struct {
  41. *ssh.Certificate `json:"omitempty"`
  42. }
  43. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  44. // base64 encoded, openssh wire format version of the certificate.
  45. func (c SSHCertificate) MarshalJSON() ([]byte, error) {
  46. if c.Certificate == nil {
  47. return []byte("null"), nil
  48. }
  49. s := base64.StdEncoding.EncodeToString(c.Certificate.Marshal())
  50. return []byte(`"` + s + `"`), nil
  51. }
  52. // SSHPublicKey represents a public key in a response object.
  53. type SSHPublicKey struct {
  54. ssh.PublicKey
  55. }
  56. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  57. // base64 encoded, openssh wire format version of the public key.
  58. func (p *SSHPublicKey) MarshalJSON() ([]byte, error) {
  59. if p == nil || p.PublicKey == nil {
  60. return []byte("null"), nil
  61. }
  62. s := base64.StdEncoding.EncodeToString(p.PublicKey.Marshal())
  63. return []byte(`"` + s + `"`), nil
  64. }
  65. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  66. // expected to be a quoted, base64 encoded, openssh wire formatted block of bytes.
  67. func (c *SSHCertificate) UnmarshalJSON(data []byte) error {
  68. var s string
  69. if err := json.Unmarshal(data, &s); err != nil {
  70. return errors.Wrap(err, "error decoding certificate")
  71. }
  72. if s == "" {
  73. c.Certificate = nil
  74. return nil
  75. }
  76. certData, err := base64.StdEncoding.DecodeString(s)
  77. if err != nil {
  78. return errors.Wrap(err, "error decoding ssh certificate")
  79. }
  80. pub, err := ssh.ParsePublicKey(certData)
  81. if err != nil {
  82. return errors.Wrap(err, "error parsing ssh certificate")
  83. }
  84. cert, ok := pub.(*ssh.Certificate)
  85. if !ok {
  86. return errors.Errorf("error decoding ssh certificate: %T is not an *ssh.Certificate", pub)
  87. }
  88. c.Certificate = cert
  89. return nil
  90. }
  91. // Validate validates the SignSSHRequest.
  92. func (s *SignSSHRequest) Validate() error {
  93. switch {
  94. case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
  95. return errors.Errorf("unknown certType %s", s.CertType)
  96. case len(s.PublicKey) == 0:
  97. return errors.New("missing or empty publicKey")
  98. case len(s.OTT) == 0:
  99. return errors.New("missing or empty ott")
  100. default:
  101. return nil
  102. }
  103. }
  104. // SignSSH is an HTTP handler that reads an SignSSHRequest with a one-time-token
  105. // (ott) from the body and creates a new SSH certificate with the information in
  106. // the request.
  107. func (h *caHandler) SignSSH(w http.ResponseWriter, r *http.Request) {
  108. var body SignSSHRequest
  109. if err := ReadJSON(r.Body, &body); err != nil {
  110. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  111. return
  112. }
  113. logOtt(w, body.OTT)
  114. if err := body.Validate(); err != nil {
  115. WriteError(w, BadRequest(err))
  116. return
  117. }
  118. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  119. if err != nil {
  120. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  121. return
  122. }
  123. var addUserPublicKey ssh.PublicKey
  124. if body.AddUserPublicKey != nil {
  125. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  126. if err != nil {
  127. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  128. return
  129. }
  130. }
  131. opts := provisioner.SSHOptions{
  132. CertType: body.CertType,
  133. Principals: body.Principals,
  134. ValidBefore: body.ValidBefore,
  135. ValidAfter: body.ValidAfter,
  136. }
  137. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  138. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  139. if err != nil {
  140. WriteError(w, Unauthorized(err))
  141. return
  142. }
  143. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  144. if err != nil {
  145. WriteError(w, Forbidden(err))
  146. return
  147. }
  148. var addUserCertificate *SSHCertificate
  149. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  150. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  151. if err != nil {
  152. WriteError(w, Forbidden(err))
  153. return
  154. }
  155. addUserCertificate = &SSHCertificate{addUserCert}
  156. }
  157. w.WriteHeader(http.StatusCreated)
  158. JSON(w, &SignSSHResponse{
  159. Certificate: SSHCertificate{cert},
  160. AddUserCertificate: addUserCertificate,
  161. })
  162. }
  163. // SSHConfig is an HTTP handler that returns the SSH public keys for user and
  164. // host certificates.
  165. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  166. config, err := h.Authority.SSHConfig()
  167. if err != nil {
  168. WriteError(w, NotFound(err))
  169. return
  170. }
  171. var host, user *SSHPublicKey
  172. if config.HostKey != nil {
  173. host = &SSHPublicKey{config.HostKey}
  174. }
  175. if config.UserKey != nil {
  176. user = &SSHPublicKey{config.UserKey}
  177. }
  178. JSON(w, &SSHConfigResponse{
  179. HostKey: host,
  180. UserKey: user,
  181. })
  182. }