ssh.go 11 KB

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