ssh.go 11 KB

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