ssh.go 13 KB

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