ssh.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. GetSSHKeys() (*authority.SSHKeys, 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. // Validate validates the SignSSHRequest.
  29. func (s *SignSSHRequest) Validate() error {
  30. switch {
  31. case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
  32. return errors.Errorf("unknown certType %s", s.CertType)
  33. case len(s.PublicKey) == 0:
  34. return errors.New("missing or empty publicKey")
  35. case len(s.OTT) == 0:
  36. return errors.New("missing or empty ott")
  37. default:
  38. return nil
  39. }
  40. }
  41. // SignSSHResponse is the response object that returns the SSH certificate.
  42. type SignSSHResponse struct {
  43. Certificate SSHCertificate `json:"crt"`
  44. AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
  45. }
  46. // SSHKeysResponse represents the response object that returns the SSH user and
  47. // host keys.
  48. type SSHKeysResponse struct {
  49. UserKey *SSHPublicKey `json:"userKey,omitempty"`
  50. HostKey *SSHPublicKey `json:"hostKey,omitempty"`
  51. }
  52. // SSHCertificate represents the response SSH certificate.
  53. type SSHCertificate struct {
  54. *ssh.Certificate `json:"omitempty"`
  55. }
  56. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  57. // base64 encoded, openssh wire format version of the certificate.
  58. func (c SSHCertificate) MarshalJSON() ([]byte, error) {
  59. if c.Certificate == nil {
  60. return []byte("null"), nil
  61. }
  62. s := base64.StdEncoding.EncodeToString(c.Certificate.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. // SSHPublicKey represents a public key in a response object.
  92. type SSHPublicKey struct {
  93. ssh.PublicKey
  94. }
  95. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  96. // base64 encoded, openssh wire format version of the public key.
  97. func (p *SSHPublicKey) MarshalJSON() ([]byte, error) {
  98. if p == nil || p.PublicKey == nil {
  99. return []byte("null"), nil
  100. }
  101. s := base64.StdEncoding.EncodeToString(p.PublicKey.Marshal())
  102. return []byte(`"` + s + `"`), nil
  103. }
  104. // UnmarshalJSON implements the json.Unmarshaler interface. The public key is
  105. // expected to be a quoted, base64 encoded, openssh wire formatted block of
  106. // bytes.
  107. func (p *SSHPublicKey) UnmarshalJSON(data []byte) error {
  108. var s string
  109. if err := json.Unmarshal(data, &s); err != nil {
  110. return errors.Wrap(err, "error decoding ssh public key")
  111. }
  112. if s == "" {
  113. p.PublicKey = nil
  114. return nil
  115. }
  116. data, err := base64.StdEncoding.DecodeString(s)
  117. if err != nil {
  118. return errors.Wrap(err, "error decoding ssh public key")
  119. }
  120. pub, err := ssh.ParsePublicKey(data)
  121. if err != nil {
  122. return errors.Wrap(err, "error parsing ssh public key")
  123. }
  124. p.PublicKey = pub
  125. return nil
  126. }
  127. // SignSSH is an HTTP handler that reads an SignSSHRequest with a one-time-token
  128. // (ott) from the body and creates a new SSH certificate with the information in
  129. // the request.
  130. func (h *caHandler) SignSSH(w http.ResponseWriter, r *http.Request) {
  131. var body SignSSHRequest
  132. if err := ReadJSON(r.Body, &body); err != nil {
  133. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  134. return
  135. }
  136. logOtt(w, body.OTT)
  137. if err := body.Validate(); err != nil {
  138. WriteError(w, BadRequest(err))
  139. return
  140. }
  141. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  142. if err != nil {
  143. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  144. return
  145. }
  146. var addUserPublicKey ssh.PublicKey
  147. if body.AddUserPublicKey != nil {
  148. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  149. if err != nil {
  150. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  151. return
  152. }
  153. }
  154. opts := provisioner.SSHOptions{
  155. CertType: body.CertType,
  156. Principals: body.Principals,
  157. ValidBefore: body.ValidBefore,
  158. ValidAfter: body.ValidAfter,
  159. }
  160. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  161. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  162. if err != nil {
  163. WriteError(w, Unauthorized(err))
  164. return
  165. }
  166. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  167. if err != nil {
  168. WriteError(w, Forbidden(err))
  169. return
  170. }
  171. var addUserCertificate *SSHCertificate
  172. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  173. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  174. if err != nil {
  175. WriteError(w, Forbidden(err))
  176. return
  177. }
  178. addUserCertificate = &SSHCertificate{addUserCert}
  179. }
  180. w.WriteHeader(http.StatusCreated)
  181. JSON(w, &SignSSHResponse{
  182. Certificate: SSHCertificate{cert},
  183. AddUserCertificate: addUserCertificate,
  184. })
  185. }
  186. // SSHKeys is an HTTP handler that returns the SSH public keys for user and host
  187. // certificates.
  188. func (h *caHandler) SSHKeys(w http.ResponseWriter, r *http.Request) {
  189. keys, err := h.Authority.GetSSHKeys()
  190. if err != nil {
  191. WriteError(w, NotFound(err))
  192. return
  193. }
  194. var host, user *SSHPublicKey
  195. if keys.HostKey != nil {
  196. host = &SSHPublicKey{PublicKey: keys.HostKey}
  197. }
  198. if keys.UserKey != nil {
  199. user = &SSHPublicKey{PublicKey: keys.UserKey}
  200. }
  201. JSON(w, &SSHKeysResponse{
  202. HostKey: host,
  203. UserKey: user,
  204. })
  205. }