ssh.go 11 KB

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