ssh.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "github.com/smallstep/certificates/templates"
  11. "golang.org/x/crypto/ssh"
  12. )
  13. // SSHAuthority is the interface implemented by a SSH CA authority.
  14. type SSHAuthority interface {
  15. SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
  16. SignSSHAddUser(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
  17. GetSSHKeys() (*authority.SSHKeys, error)
  18. GetSSHConfig(typ string) ([]templates.Output, error)
  19. }
  20. // SignSSHRequest is the request body of an SSH certificate request.
  21. type SignSSHRequest struct {
  22. PublicKey []byte `json:"publicKey"` //base64 encoded
  23. OTT string `json:"ott"`
  24. CertType string `json:"certType,omitempty"`
  25. Principals []string `json:"principals,omitempty"`
  26. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  27. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  28. AddUserPublicKey []byte `json:"addUserPublicKey,omitempty"`
  29. }
  30. // Validate validates the SignSSHRequest.
  31. func (s *SignSSHRequest) Validate() error {
  32. switch {
  33. case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
  34. return errors.Errorf("unknown certType %s", s.CertType)
  35. case len(s.PublicKey) == 0:
  36. return errors.New("missing or empty publicKey")
  37. case len(s.OTT) == 0:
  38. return errors.New("missing or empty ott")
  39. default:
  40. return nil
  41. }
  42. }
  43. // SignSSHResponse is the response object that returns the SSH certificate.
  44. type SignSSHResponse struct {
  45. Certificate SSHCertificate `json:"crt"`
  46. AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
  47. }
  48. // SSHKeysResponse represents the response object that returns the SSH user and
  49. // host keys.
  50. type SSHKeysResponse struct {
  51. UserKey *SSHPublicKey `json:"userKey,omitempty"`
  52. HostKey *SSHPublicKey `json:"hostKey,omitempty"`
  53. }
  54. // SSHCertificate represents the response SSH certificate.
  55. type SSHCertificate struct {
  56. *ssh.Certificate `json:"omitempty"`
  57. }
  58. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  59. // base64 encoded, openssh wire format version of the certificate.
  60. func (c SSHCertificate) MarshalJSON() ([]byte, error) {
  61. if c.Certificate == nil {
  62. return []byte("null"), nil
  63. }
  64. s := base64.StdEncoding.EncodeToString(c.Certificate.Marshal())
  65. return []byte(`"` + s + `"`), nil
  66. }
  67. // UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
  68. // expected to be a quoted, base64 encoded, openssh wire formatted block of bytes.
  69. func (c *SSHCertificate) UnmarshalJSON(data []byte) error {
  70. var s string
  71. if err := json.Unmarshal(data, &s); err != nil {
  72. return errors.Wrap(err, "error decoding certificate")
  73. }
  74. if s == "" {
  75. c.Certificate = nil
  76. return nil
  77. }
  78. certData, err := base64.StdEncoding.DecodeString(s)
  79. if err != nil {
  80. return errors.Wrap(err, "error decoding ssh certificate")
  81. }
  82. pub, err := ssh.ParsePublicKey(certData)
  83. if err != nil {
  84. return errors.Wrap(err, "error parsing ssh certificate")
  85. }
  86. cert, ok := pub.(*ssh.Certificate)
  87. if !ok {
  88. return errors.Errorf("error decoding ssh certificate: %T is not an *ssh.Certificate", pub)
  89. }
  90. c.Certificate = cert
  91. return nil
  92. }
  93. // SSHPublicKey represents a public key in a response object.
  94. type SSHPublicKey struct {
  95. ssh.PublicKey
  96. }
  97. // MarshalJSON implements the json.Marshaler interface. Returns a quoted,
  98. // base64 encoded, openssh wire format version of the public key.
  99. func (p *SSHPublicKey) MarshalJSON() ([]byte, error) {
  100. if p == nil || p.PublicKey == nil {
  101. return []byte("null"), nil
  102. }
  103. s := base64.StdEncoding.EncodeToString(p.PublicKey.Marshal())
  104. return []byte(`"` + s + `"`), nil
  105. }
  106. // UnmarshalJSON implements the json.Unmarshaler interface. The public key is
  107. // expected to be a quoted, base64 encoded, openssh wire formatted block of
  108. // bytes.
  109. func (p *SSHPublicKey) UnmarshalJSON(data []byte) error {
  110. var s string
  111. if err := json.Unmarshal(data, &s); err != nil {
  112. return errors.Wrap(err, "error decoding ssh public key")
  113. }
  114. if s == "" {
  115. p.PublicKey = nil
  116. return nil
  117. }
  118. data, err := base64.StdEncoding.DecodeString(s)
  119. if err != nil {
  120. return errors.Wrap(err, "error decoding ssh public key")
  121. }
  122. pub, err := ssh.ParsePublicKey(data)
  123. if err != nil {
  124. return errors.Wrap(err, "error parsing ssh public key")
  125. }
  126. p.PublicKey = pub
  127. return nil
  128. }
  129. // Template represents the output of a template.
  130. type Template = templates.Output
  131. // SSHConfigRequest is the request body used to get the SSH configuration
  132. // templates.
  133. type SSHConfigRequest struct {
  134. Type string `json:"type"`
  135. }
  136. // Validate checks the values of the SSHConfigurationRequest.
  137. func (r *SSHConfigRequest) Validate() error {
  138. switch r.Type {
  139. case "":
  140. r.Type = provisioner.SSHUserCert
  141. return nil
  142. case provisioner.SSHUserCert, provisioner.SSHHostCert:
  143. return nil
  144. default:
  145. return errors.Errorf("unsupported type %s", r.Type)
  146. }
  147. }
  148. // SSHConfigResponse is the response that returns the rendered templates.
  149. type SSHConfigResponse struct {
  150. UserTemplates []Template `json:"userTemplates,omitempty"`
  151. HostTemplates []Template `json:"hostTemplates,omitempty"`
  152. }
  153. // SignSSH is an HTTP handler that reads an SignSSHRequest with a one-time-token
  154. // (ott) from the body and creates a new SSH certificate with the information in
  155. // the request.
  156. func (h *caHandler) SignSSH(w http.ResponseWriter, r *http.Request) {
  157. var body SignSSHRequest
  158. if err := ReadJSON(r.Body, &body); err != nil {
  159. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  160. return
  161. }
  162. logOtt(w, body.OTT)
  163. if err := body.Validate(); err != nil {
  164. WriteError(w, BadRequest(err))
  165. return
  166. }
  167. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  168. if err != nil {
  169. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  170. return
  171. }
  172. var addUserPublicKey ssh.PublicKey
  173. if body.AddUserPublicKey != nil {
  174. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  175. if err != nil {
  176. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  177. return
  178. }
  179. }
  180. opts := provisioner.SSHOptions{
  181. CertType: body.CertType,
  182. Principals: body.Principals,
  183. ValidBefore: body.ValidBefore,
  184. ValidAfter: body.ValidAfter,
  185. }
  186. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  187. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  188. if err != nil {
  189. WriteError(w, Unauthorized(err))
  190. return
  191. }
  192. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  193. if err != nil {
  194. WriteError(w, Forbidden(err))
  195. return
  196. }
  197. var addUserCertificate *SSHCertificate
  198. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  199. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  200. if err != nil {
  201. WriteError(w, Forbidden(err))
  202. return
  203. }
  204. addUserCertificate = &SSHCertificate{addUserCert}
  205. }
  206. w.WriteHeader(http.StatusCreated)
  207. JSON(w, &SignSSHResponse{
  208. Certificate: SSHCertificate{cert},
  209. AddUserCertificate: addUserCertificate,
  210. })
  211. }
  212. // SSHKeys is an HTTP handler that returns the SSH public keys for user and host
  213. // certificates.
  214. func (h *caHandler) SSHKeys(w http.ResponseWriter, r *http.Request) {
  215. keys, err := h.Authority.GetSSHKeys()
  216. if err != nil {
  217. WriteError(w, NotFound(err))
  218. return
  219. }
  220. var host, user *SSHPublicKey
  221. if keys.HostKey != nil {
  222. host = &SSHPublicKey{PublicKey: keys.HostKey}
  223. }
  224. if keys.UserKey != nil {
  225. user = &SSHPublicKey{PublicKey: keys.UserKey}
  226. }
  227. JSON(w, &SSHKeysResponse{
  228. HostKey: host,
  229. UserKey: user,
  230. })
  231. }
  232. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  233. // and servers.
  234. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  235. var body SSHConfigRequest
  236. if err := ReadJSON(r.Body, &body); err != nil {
  237. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  238. return
  239. }
  240. if err := body.Validate(); err != nil {
  241. WriteError(w, BadRequest(err))
  242. return
  243. }
  244. ts, err := h.Authority.GetSSHConfig(body.Type)
  245. if err != nil {
  246. WriteError(w, InternalServerError(err))
  247. return
  248. }
  249. var config SSHConfigResponse
  250. switch body.Type {
  251. case provisioner.SSHUserCert:
  252. config.UserTemplates = ts
  253. case provisioner.SSHHostCert:
  254. config.UserTemplates = ts
  255. default:
  256. WriteError(w, InternalServerError(errors.New("it should hot get here")))
  257. return
  258. }
  259. JSON(w, config)
  260. }