ssh.go 9.4 KB

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