ssh.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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, data map[string]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. Data map[string]string `json:"data"`
  136. }
  137. // Validate checks the values of the SSHConfigurationRequest.
  138. func (r *SSHConfigRequest) Validate() error {
  139. switch r.Type {
  140. case "":
  141. r.Type = provisioner.SSHUserCert
  142. return nil
  143. case provisioner.SSHUserCert, provisioner.SSHHostCert:
  144. return nil
  145. default:
  146. return errors.Errorf("unsupported type %s", r.Type)
  147. }
  148. }
  149. // SSHConfigResponse is the response that returns the rendered templates.
  150. type SSHConfigResponse struct {
  151. UserTemplates []Template `json:"userTemplates,omitempty"`
  152. HostTemplates []Template `json:"hostTemplates,omitempty"`
  153. }
  154. // SignSSH is an HTTP handler that reads an SignSSHRequest with a one-time-token
  155. // (ott) from the body and creates a new SSH certificate with the information in
  156. // the request.
  157. func (h *caHandler) SignSSH(w http.ResponseWriter, r *http.Request) {
  158. var body SignSSHRequest
  159. if err := ReadJSON(r.Body, &body); err != nil {
  160. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  161. return
  162. }
  163. logOtt(w, body.OTT)
  164. if err := body.Validate(); err != nil {
  165. WriteError(w, BadRequest(err))
  166. return
  167. }
  168. publicKey, err := ssh.ParsePublicKey(body.PublicKey)
  169. if err != nil {
  170. WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
  171. return
  172. }
  173. var addUserPublicKey ssh.PublicKey
  174. if body.AddUserPublicKey != nil {
  175. addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
  176. if err != nil {
  177. WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
  178. return
  179. }
  180. }
  181. opts := provisioner.SSHOptions{
  182. CertType: body.CertType,
  183. Principals: body.Principals,
  184. ValidBefore: body.ValidBefore,
  185. ValidAfter: body.ValidAfter,
  186. }
  187. ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
  188. signOpts, err := h.Authority.Authorize(ctx, body.OTT)
  189. if err != nil {
  190. WriteError(w, Unauthorized(err))
  191. return
  192. }
  193. cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
  194. if err != nil {
  195. WriteError(w, Forbidden(err))
  196. return
  197. }
  198. var addUserCertificate *SSHCertificate
  199. if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
  200. addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
  201. if err != nil {
  202. WriteError(w, Forbidden(err))
  203. return
  204. }
  205. addUserCertificate = &SSHCertificate{addUserCert}
  206. }
  207. w.WriteHeader(http.StatusCreated)
  208. JSON(w, &SignSSHResponse{
  209. Certificate: SSHCertificate{cert},
  210. AddUserCertificate: addUserCertificate,
  211. })
  212. }
  213. // SSHKeys is an HTTP handler that returns the SSH public keys for user and host
  214. // certificates.
  215. func (h *caHandler) SSHKeys(w http.ResponseWriter, r *http.Request) {
  216. keys, err := h.Authority.GetSSHKeys()
  217. if err != nil {
  218. WriteError(w, NotFound(err))
  219. return
  220. }
  221. var host, user *SSHPublicKey
  222. if keys.HostKey != nil {
  223. host = &SSHPublicKey{PublicKey: keys.HostKey}
  224. }
  225. if keys.UserKey != nil {
  226. user = &SSHPublicKey{PublicKey: keys.UserKey}
  227. }
  228. JSON(w, &SSHKeysResponse{
  229. HostKey: host,
  230. UserKey: user,
  231. })
  232. }
  233. // SSHConfig is an HTTP handler that returns rendered templates for ssh clients
  234. // and servers.
  235. func (h *caHandler) SSHConfig(w http.ResponseWriter, r *http.Request) {
  236. var body SSHConfigRequest
  237. if err := ReadJSON(r.Body, &body); err != nil {
  238. WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
  239. return
  240. }
  241. if err := body.Validate(); err != nil {
  242. WriteError(w, BadRequest(err))
  243. return
  244. }
  245. ts, err := h.Authority.GetSSHConfig(body.Type, body.Data)
  246. if err != nil {
  247. WriteError(w, InternalServerError(err))
  248. return
  249. }
  250. var config SSHConfigResponse
  251. switch body.Type {
  252. case provisioner.SSHUserCert:
  253. config.UserTemplates = ts
  254. case provisioner.SSHHostCert:
  255. config.UserTemplates = ts
  256. default:
  257. WriteError(w, InternalServerError(errors.New("it should hot get here")))
  258. return
  259. }
  260. JSON(w, config)
  261. }